List of usage examples for java.io PrintWriter println
public void println(Object x)
From source file:com.samczsun.helios.Helios.java
public static void relaunchAsAdmin() throws IOException, InterruptedException, URISyntaxException { File currentJarLocation = getJarLocation(); File javawLocation = getJavawLocation(); if (currentJarLocation == null) { SWTUtil.showMessage("Could not relaunch as admin - unable to find Helios.jar"); return;//w w w. j a va 2 s . co m } if (javawLocation == null) { SWTUtil.showMessage("Could not relaunch as admin - unable to find javaw.exe"); return; } File tempVBSFile = File.createTempFile("tmpvbs", ".vbs"); PrintWriter writer = new PrintWriter(tempVBSFile); writer.println("Set objShell = CreateObject(\"Wscript.Shell\")"); writer.println("strPath = Wscript.ScriptFullName"); writer.println("Set objFSO = CreateObject(\"Scripting.FileSystemObject\")"); writer.println("Set objFile = objFSO.GetFile(strPath)"); writer.println("strFolder = objFSO.GetParentFolderName(objFile)"); writer.println("Set UAC = CreateObject(\"Shell.Application\")"); writer.println("UAC.ShellExecute \"\"\"" + javawLocation.getAbsolutePath() + "\"\"\", \"-jar \"\"" + currentJarLocation.getAbsolutePath() + "\"\"\", strFolder, \"runas\", 1"); writer.println("WScript.Quit 0"); writer.close(); Process process = Runtime.getRuntime().exec("cscript " + tempVBSFile.getAbsolutePath()); process.waitFor(); System.exit(process.exitValue()); }
From source file:de.zib.scalaris.examples.wikipedia.data.xml.Main.java
/** * Filters all pages in the Wikipedia XML dump from the given file and * creates a list of page names belonging to certain categories. * /*from w w w . j a v a 2s . c om*/ * @param filename * @param args * * @throws RuntimeException * @throws IOException * @throws SAXException * @throws FileNotFoundException */ private static void doFilter(String filename, String[] args) throws RuntimeException, IOException, SAXException, FileNotFoundException { int i = 0; int recursionLvl = 1; if (args.length > i) { try { recursionLvl = Integer.parseInt(args[i]); } catch (NumberFormatException e) { System.err.println("no number: " + args[i]); System.exit(-1); } } ++i; // a timestamp in ISO8601 format Calendar maxTime = null; if (args.length > i && !args[i].isEmpty()) { try { maxTime = Revision.stringToCalendar(args[i]); } catch (IllegalArgumentException e) { System.err.println("no date in ISO8601: " + args[i]); System.exit(-1); } } ++i; String pageListFileName = ""; if (args.length > i && !args[i].isEmpty()) { pageListFileName = args[i]; } else { System.err.println("need a pagelist file name for filter; arguments given: " + Arrays.toString(args)); System.exit(-1); } ++i; Set<String> allowedPages = new HashSet<String>(); allowedPages.add("Main Page"); String allowedPagesFileName = ""; if (args.length > i && !args[i].isEmpty()) { allowedPagesFileName = args[i]; addFromFile(allowedPages, allowedPagesFileName); } ++i; LinkedList<String> rootCategories = new LinkedList<String>(); if (args.length > i) { for (String rCat : Arrays.asList(args).subList(i, args.length)) { if (!rCat.isEmpty()) { rootCategories.add(rCat); } } } WikiDumpHandler.println(System.out, "filtering by categories " + rootCategories.toString() + " ..."); WikiDumpHandler.println(System.out, " wiki dump : " + filename); WikiDumpHandler.println(System.out, " max time : " + maxTime); WikiDumpHandler.println(System.out, " allowed pages : " + allowedPagesFileName); WikiDumpHandler.println(System.out, " recursion lvl : " + recursionLvl); SortedSet<String> pages = getPageList(filename, maxTime, allowedPages, rootCategories, recursionLvl); do { FileWriter outFile = new FileWriter(pageListFileName); PrintWriter out = new PrintWriter(outFile); for (String page : pages) { out.println(page); } out.close(); } while (false); }
From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftFileWriterUtil.java
private static void writeExperimentContact(ExperimentContact c, PrintWriter out) { final Person p = c.getPerson(); out.print("!Series_contributor="); out.print(p.getFirstName());/*ww w . j a v a 2 s. c om*/ out.print(','); if (StringUtils.isNotBlank(p.getMiddleInitials())) { out.print(p.getMiddleInitials()); out.print(","); } out.println(p.getLastName()); }
From source file:io.warp10.worf.WorfInteractive.java
private static String readHost(ConsoleReader reader, PrintWriter out, String prompt) { try {// ww w .ja va2 s . c o m String inputString = readInputString(reader, out, prompt); if (InetAddresses.isInetAddress(inputString)) { return inputString; } out.println("Error, " + inputString + " is not a valid inet address"); } catch (Exception exp) { if (WorfCLI.verbose) { exp.printStackTrace(); } out.println("Error, unable to read the host. error=" + exp.getMessage()); } return null; }
From source file:com.jolbox.benchmark.BenchmarkLaunch.java
/** * @param results/* w w w .j a v a 2s.co m*/ * @param delay * @param statementBenchmark * @param noC3P0 * @throws IOException */ private static void doPlotLineGraph(long[][] results, int delay, boolean statementBenchmark, boolean noC3P0) throws IOException { String title = "Multi-Thread test (" + delay + "ms delay)"; if (statementBenchmark) { title += "\n(with PreparedStatements tests)"; } String fname = System.getProperty("java.io.tmpdir") + File.separator + "bonecp-multithread-" + delay + "ms-delay"; if (statementBenchmark) { fname += "-with-preparedstatements"; } fname += "-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads; if (noC3P0) { fname += "-noC3P0"; } PrintWriter out = new PrintWriter(new FileWriter(fname + ".txt")); fname += ".png"; XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < ConnectionPoolType.values().length; i++) { // if (!ConnectionPoolType.values()[i].isEnabled() || (noC3P0 && ConnectionPoolType.values()[i].equals(ConnectionPoolType.C3P0))) { continue; } XYSeries series = new XYSeries(ConnectionPoolType.values()[i].toString()); out.println(ConnectionPoolType.values()[i].toString()); for (int j = 1 + BenchmarkTests.stepping; j < results[i].length; j += BenchmarkTests.stepping) { series.add(j, results[i][j]); out.println(j + "," + results[i][j]); } dataset.addSeries(series); } out.close(); // Generate the graph JFreeChart chart = ChartFactory.createXYLineChart(title, // Title "threads", // x-axis Label "time (ns)", // y-axis Label dataset, // Dataset PlotOrientation.VERTICAL, // Plot Orientation true, // Show Legend true, // Use tooltips false // Configure chart to generate URLs? ); XYPlot plot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); plot.setRenderer(renderer); renderer.setSeriesPaint(0, Color.BLUE); renderer.setSeriesPaint(1, Color.YELLOW); renderer.setSeriesPaint(2, Color.BLACK); renderer.setSeriesPaint(3, Color.DARK_GRAY); renderer.setSeriesPaint(4, Color.MAGENTA); renderer.setSeriesPaint(5, Color.RED); renderer.setSeriesPaint(6, Color.LIGHT_GRAY); // renderer.setSeriesShapesVisible(1, true); // renderer.setSeriesShapesVisible(2, true); try { ChartUtilities.saveChartAsPNG(new File(fname), chart, 1024, 768); System.out.println("******* Saved chart to: " + fname); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } }
From source file:co.raveesh.yspages.YSScraper.java
/** * This function writes a JSONObject to the required output file * @param fileName Output file name. The /output directory and .json extension are added by this method * @param object The required output content in JSONObject form *//*from w w w .j a v a 2 s . c o m*/ private static void writeToFile(String fileName, JSONObject object) { PrintWriter writer = null; try { writer = new PrintWriter(Constants.OUTPUT_BASE + fileName + ".json", "UTF-8"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } writer.println(object.toString()); writer.close(); }
From source file:Main.java
/** * This method is used to send a XML request file to web server to process the request and return * xml response containing event id./*ww w . j ava 2s .c o m*/ */ public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception { System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server ......."); InputStream in = null; BufferedReader bufferedReader = null; OutputStream out = null; PrintWriter printWriter = null; StringBuffer responseMessageBuffer = new StringBuffer(""); try { URL url = new URL(postUrl); URLConnection con = url.openConnection(); // Prepare for both input and output con.setDoInput(true); con.setDoOutput(true); // Turn off caching con.setUseCaches(false); con.setRequestProperty("Content-Type", "text/xml"); con.setReadTimeout(readTimeout); out = con.getOutputStream(); // Write the arguments as post data printWriter = new PrintWriter(out); printWriter.println(xml); printWriter.flush(); //Process response and return back to caller function in = con.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(in)); String tempStr = null; int tempClearResponseMessageBufferCounter = 0; while ((tempStr = bufferedReader.readLine()) != null) { tempClearResponseMessageBufferCounter++; //clear the buffer for the first time if (tempClearResponseMessageBufferCounter == 1) responseMessageBuffer.setLength(0); responseMessageBuffer.append(tempStr); } } catch (Exception ex) { throw ex; } finally { System.out.println("Calling finally in POSTXML"); try { if (in != null) in.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Input Stream in try"); } try { if (out != null) out.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Output Stream in try"); } } System.out.println("XMLUtils.postXMLWithTimeout: end ......."); return responseMessageBuffer.toString(); }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Find the startup file in one of several locations and by one * of several names, then run the commands found therein. * * @param parser the command interpreter. * @throws IOException if reading file fails. *//*from ww w .j av a 2 s . c o m*/ private static void runStartupFile(CommandParser parser, PrintWriter consoleOutput) throws IOException { File[] files = { new File(System.getProperty("user.dir"), ".jswatrc"), new File(System.getProperty("user.dir"), "jswat.ini"), new File(System.getProperty("user.home"), ".jswatrc"), new File(System.getProperty("user.home"), "jswat.ini") }; for (File file : files) { if (file.canRead()) { consoleOutput.println("Executing startup file: " + file.getAbsolutePath()); BufferedReader br = new BufferedReader(new FileReader(file)); try { String line = br.readLine(); while (line != null) { line = line.trim(); if (!line.isEmpty() && !line.startsWith("#")) { performCommand(consoleOutput, parser, line); } line = br.readLine(); } } finally { br.close(); } // We just read the first file we find and stop. break; } } }
From source file:com.jaeksoft.searchlib.Logging.java
public final static String readLogs(int lines, String fileName) throws IOException { if (fileName == null) return null; File logFile = new File(getLogDirectory(), fileName); if (!logFile.exists()) return null; FileReader fr = null;/* w w w . j a v a2 s . c o m*/ BufferedReader br = null; StringWriter sw = null; PrintWriter pw = null; LinkedList<String> list = new LinkedList<String>(); try { fr = new FileReader(logFile); br = new BufferedReader(fr); String line = null; int size = 0; while ((line = br.readLine()) != null) { list.add(line); if (size++ > lines) list.remove(); } sw = new StringWriter(); pw = new PrintWriter(sw); for (String l : list) pw.println(StringEscapeUtils.escapeJava(l)); return sw.toString(); } finally { IOUtils.close(br, fr, pw, sw); } }
From source file:de.tudarmstadt.lt.seg.app.Segmenter.java
public static void split_and_tokenize(Reader reader, String docid, ISentenceSplitter sentenceSplitter, ITokenizer tokenizer, int level_filter, int level_normalize, boolean merge_types, boolean merge_tokens, String separator_sentence, String separator_token, String separator_desc, PrintWriter writer) { try {/* w w w. j av a 2 s.c om*/ final StringBuffer buf = new StringBuffer(); // used for checking of stream is empty; take care when not running sequentially but in parallel! sentenceSplitter.init(reader).stream().sequential().forEach(sentence_segment -> { if (DEBUG) { writer.format("%s%s", docid, separator_desc); writer.println(sentence_segment.toString()); writer.print(separator_sentence); } if (sentence_segment.type != SegmentType.SENTENCE) return; tokenizer.init(sentence_segment.asString()); Stream<String> tokens = null; if (DEBUG) tokens = tokenizer.stream().map(x -> x.toString() + separator_token); else tokens = StreamSupport.stream(tokenizer .filteredAndNormalizedTokens(level_filter, level_normalize, merge_types, merge_tokens) .spliterator(), false).map(x -> x + separator_token); Spliterator<String> spliterator = tokens.spliterator(); tokens = StreamSupport.stream(spliterator, false); buf.setLength(0); boolean empty = !spliterator.tryAdvance(x -> { buf.append(x); }); if (empty) return; synchronized (writer) { // writer.write(Thread.currentThread().getId() + "\t"); writer.format("%s%s", docid, separator_desc); writer.print(buf); tokens.forEach(writer::print); writer.print(separator_sentence); writer.flush(); } }); } catch (Exception e) { Throwable t = e; while (t != null) { System.err.format("%s: %s%n", e.getClass(), e.getMessage()); t = e.getCause(); } } }