private void sendProcessingError(Throwable t, ServletResponse response) { String stackTrace = getStackTrace(t); if (stackTrace != null && !stackTrace.equals("")) { try { response.setContentType("text/html"); PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps); pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N // PENDING! Localize this for next official release pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); pw.print(stackTrace); pw.print("</pre></body>\n</html>"); // NOI18N pw.close(); ps.close(); response.getOutputStream().close(); ; } catch (Exception ex) { } } else { try { PrintStream ps = new PrintStream(response.getOutputStream()); t.printStackTrace(ps); ps.close(); response.getOutputStream().close(); ; } catch (Exception ex) { } } }
/** main loop - periodically copy location data into Lua and evaluate zone positions */ private void mainloop() { try { while (!end) { try { if (gps.getLatitude() != player.position.latitude || gps.getLongitude() != player.position.longitude || gps.getAltitude() != player.position.altitude) { player.refreshLocation(); } cartridge.tick(); } catch (Exception e) { stacktrace(e); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } if (log != null) log.close(); } catch (Throwable t) { ui.end(); stacktrace(t); } finally { instance = null; state = null; if (eventRunner != null) eventRunner.kill(); eventRunner = null; } }
/** * automatically generate non-existing help html files for existing commands in the CommandLoader * * @param cl the CommandLoader where you look for the existing commands */ public void createHelpText(CommandLoader cl) { File dir = new File((getClass().getResource("..").getPath())); dir = new File(dir, language); if (!dir.exists() && !dir.mkdirs()) { System.out.println("Failed to create " + dir.getAbsolutePath()); return; } for (String mnemo : cl.getMnemoList()) { if (!exists(mnemo)) { File file = new File(dir, mnemo + ".htm"); try { file.createNewFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); PrintStream ps = new PrintStream(os); ps.println("<html>\n<head>\n<title>" + mnemo + "\n</title>\n</head>\n<body>"); ps.println("Command: " + mnemo.toUpperCase() + "<br>"); ps.println("arguments: <br>"); ps.println("effects: <br>"); ps.println("flags to be set: <br>"); ps.println("approx. clockcycles: <br>"); ps.println("misc: <br>"); ps.println("</body>\n</html>"); ps.flush(); ps.close(); } catch (IOException e) { System.out.println("failed to create " + file.getAbsolutePath()); } } } }
public static void main(String[] args) { String tokensFile = args[0]; String progFile = args[1]; String tempFile = "CAMLE_TEMP.txt"; List<String> tokenName = new ArrayList<String>(); List<Integer> tokenType = new ArrayList<Integer>(); List<String> nameOf = new ArrayList<String>(); String line; boolean skipping = false; try { int nTokens = readTokensFile(tokensFile, tokenName, tokenType, nameOf); BufferedReader in = new BufferedReader(new FileReader(progFile)); PrintStream o = new PrintStream(new FileOutputStream(tempFile)); while ((line = in.readLine()) != null) { if (line.equals("// CAMLE TOKENS END")) { skipping = false; } if (!skipping) { o.println(line); } if (line.equals("// CAMLE TOKENS BEGIN")) { skipping = true; writeTokensCode(o, nTokens, tokenName, tokenType, nameOf); } } in.close(); o.close(); new File(tempFile).renameTo(new File(progFile)); } catch (Exception e) { System.out.println(e.toString()); System.exit(1); } }
public void save(File f) throws IOException { PrintStream ps = new PrintStream(new FileOutputStream(f)); String[] genes = genes(); Vector<Map<String, Double>> maps = new Vector<Map<String, Double>>(); for (int j = 0; j < coefs.size(); j++) { maps.add(coefs.get(j).geneValues(args.compare)); } ps.print("gene"); for (int i = 0; i < coefs.size(); i++) { ps.print(" " + keys.get(i)); } ps.println(); for (int i = 0; i < genes.length; i++) { ps.print(String.format("%s", genes[i])); for (int j = 0; j < coefs.size(); j++) { Map<String, Double> map = maps.get(j); Double value = map.containsKey(genes[i]) ? map.get(genes[i]) : null; ps.print(String.format(" %s", value != null ? String.format("%.2f", value) : "N/A")); } ps.println(); } ps.println(); ps.close(); }
public void init() { try { url = new URL(urlStr); // 创建一个代理服务器对象 proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); // 使用指定的代理服务器打开连接 conn = url.openConnection(proxy); // 设置超时时长。 conn.setConnectTimeout(5000); scan = new Scanner(conn.getInputStream()); // 初始化输出流 ps = new PrintStream("Index.htm"); while (scan.hasNextLine()) { String line = scan.nextLine(); // 在控制台输出网页资源内容 System.out.println(line); // 将网页资源内容输出到指定输出流 ps.println(line); } } catch (MalformedURLException ex) { System.out.println(urlStr + "不是有效的网站地址!"); } catch (IOException ex) { ex.printStackTrace(); } // 关闭资源 finally { if (ps != null) { ps.close(); } } }
@Test public void canFollowLogfile() throws IOException { File tempFile = File.createTempFile("commons-io", "", new File(System.getProperty("java.io.tmpdir"))); tempFile.deleteOnExit(); System.out.println("Temp file = " + tempFile.getAbsolutePath()); PrintStream log = new PrintStream(tempFile); LogfileFollower follower = new LogfileFollower(tempFile); List<String> lines; // Empty file: lines = follower.newLines(); assertEquals(0, lines.size()); // Write two lines: log.println("Line 1"); log.println("Line 2"); lines = follower.newLines(); assertEquals(2, lines.size()); assertEquals("Line 2", lines.get(1)); // Write one more line: log.println("Line 3"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 3", lines.get(0)); // Write one and a half line and finish later: log.println("Line 4"); log.print("Line 5 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); // End last line and start a new one: log.println(" end"); log.print("Line 6 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 5 begin end", lines.get(0)); // End last line: log.println(" end"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 6 begin end", lines.get(0)); // A line only missing a newline: log.print("Line 7"); lines = follower.newLines(); assertEquals(0, lines.size()); log.println(); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 7", lines.get(0)); // Delete: log.close(); lines = follower.newLines(); assertEquals(0, lines.size()); }
public void run() { if (clientSocket == null) { return; } PrintStream out = null; Utilities.printMsg("creating output stream"); try { out = new PrintStream(clientSocket.getOutputStream()); } catch (IOException e) { System.err.println("Error binding output to socket, " + e); System.exit(1); } Utilities.printMsg("writing current date"); Date d = new Date(); out.println(d); try { out.close(); clientSocket.close(); } catch (IOException e) { } }
/** Destroys the server stored list. */ @Override public void destroy() { stopped = true; try { if (connection != null) { connection.shutdownInput(); connection.close(); connection = null; } } catch (IOException e) { } try { if (connectionReader != null) { connectionReader.close(); connectionReader = null; } } catch (IOException ex) { } if (connectionWriter != null) { connectionWriter.close(); connectionWriter = null; } }
public void saveFile(File f) throws IOException { PrintStream ps = new PrintStream(new FileOutputStream(f)); ps.print("ID"); for (Column c : cols) { ps.print(String.format("\t%s", c.id)); } ps.println(); for (int i = 0; i < samples.size(); i++) { ps.print(samples.get(i)); for (int j = 0; j < cols.size(); j++) { Float ff = cols.get(j).values.get(i); if (ff == null) { ps.print("\tnull"); } else { ps.print(String.format("\t%.2f", ff)); } } ps.println(); if (i > 0) { if (i % 100 == 0) { System.out.print("."); System.out.flush(); } } } System.out.println(); ps.close(); }
private static void outputProbes(Iterator<ProbeLine> lines, File f) throws IOException { PrintStream ps = new PrintStream(new FileOutputStream(f)); while (lines.hasNext()) { ProbeLine line = lines.next(); ps.println(line.toString()); } ps.close(); }
public static void writeLinesToFile(File file, List<?> lines) throws Exception { PrintStream output = new PrintStream(new FileOutputStream(file)); for (Iterator<?> iterator = lines.iterator(); iterator.hasNext(); ) { String line = (String) iterator.next(); output.println(line); } output.close(); }
/** * Closes down connections to the underlying process. This method will be used only if the * supporting Java Native Interface library could be loaded. */ private synchronized void native_close(PrintStream out) { try { in.close(); out.flush(); out.close(); } catch (IOException ioe) { } }
public boolean parseAndValidate(String args) throws CommandLineException { PrintStream printStream = getNullPrintStream(); try { return getCommand().validateCommandLine(safeSplit(args), printStream); } finally { printStream.close(); } }
public void sendTekst(String kommando, String data) throws IOException { Socket df = skafDataforbindelse(); PrintStream dataUd = new PrintStream(df.getOutputStream()); sendKommando(kommando); // f.eks STOR fil.txt dataUd.print(data); dataUd.close(); df.close(); læsSvar(); }
public static void createFileOfRandomIntegers(String outputFileName) throws IOException { PrintStream printstream; printstream = new PrintStream(outputFileName); int numberOfIntegers = (int) (Math.random() * 100) % 10 + 1; printstream.println(numberOfIntegers); for (int i = 0; i < numberOfIntegers; i++) printstream.println((int) (Math.random() * 1000) % 100 + 1); printstream.close(); }
private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) { CmdlineRemoteProto.Message lastMessage = null; try { if (error != null) { Throwable cause = error.getCause(); if (cause == null) { cause = error; } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(out); try { cause.printStackTrace(stream); } finally { stream.close(); } final StringBuilder messageText = new StringBuilder(); messageText .append("Internal error: (") .append(cause.getClass().getName()) .append(") ") .append(cause.getMessage()); final String trace = out.toString(); if (!trace.isEmpty()) { messageText.append("\n").append(trace); } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause)); } else { CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS; if (myCanceled) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED; } else if (hadBuildErrors) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS; } else if (!markedUptodateFiles) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE; } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status)); } } catch (Throwable e) { lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e)); } finally { try { Channels.write(myChannel, lastMessage).await(); } catch (InterruptedException e) { LOG.info(e); } } }
/** Close the serial port. */ public void delete() { // Close the serial port try { if (inputStream != null) inputStream.close(); outputStream.close(); } catch (IOException e) { } mbedSerialPort.removeEventListener(); mbedSerialPort.close(); mbedPort.close(); }
public ExitCode build( final CompileContext context, final ModuleChunk chunk, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, OutputConsumer outputConsumer) throws ProjectBuildException { if (!IS_ENABLED.get(context, Boolean.TRUE)) { return ExitCode.NOTHING_DONE; } try { final Map<File, ModuleBuildTarget> filesToCompile = new THashMap<File, ModuleBuildTarget>(FileUtil.FILE_HASHING_STRATEGY); dirtyFilesHolder.processDirtyFiles( new FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget>() { public boolean apply( ModuleBuildTarget target, File file, JavaSourceRootDescriptor descriptor) throws IOException { if (JAVA_SOURCES_FILTER.accept(file)) { filesToCompile.put(file, target); } return true; } }); if (context.isMake()) { final ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger(); if (logger.isEnabled()) { if (filesToCompile.size() > 0) { logger.logCompiledFiles(filesToCompile.keySet(), BUILDER_NAME, "Compiling files:"); } } } return compile(context, chunk, dirtyFilesHolder, filesToCompile.keySet(), outputConsumer); } catch (ProjectBuildException e) { throw e; } catch (Exception e) { String message = e.getMessage(); if (message == null) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(out); try { e.printStackTrace(stream); } finally { stream.close(); } message = "Internal error: \n" + out.toString(); } context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message)); throw new ProjectBuildException(message, e); } }
// // Runnable interface // public void run() { // output all active probes for (PerformanceProbe probe : list(ALL_RECORDERS)) { probe.output("F"); } // close output if not standard output if (!outputStream.equals(System.out)) { outputStream.close(); } }
/** * @brief Save auctions out to the savefile, in XML format. * <p>Similar to the loadAuctions code, this would be nice if it were abstracted to write to * any outputstream, allowing us to write to a remote node to update it with our auctions and * snipes. * @return - true if it successfully saved, false if an error occurred. */ public boolean saveAuctions() { XMLElement auctionsData = AuctionServerManager.getInstance().toXML(); String oldSave = JConfig.queryConfiguration("savefile", "auctions.xml"); String saveFilename = JConfig.getCanonicalFile( JConfig.queryConfiguration("savefile", "auctions.xml"), "jbidwatcher", false); String newSave = saveFilename; // If there's no data to save, then pretend we did it. if (auctionsData == null) return true; ensureDirectories(saveFilename); boolean swapFiles = needSwapSaves(saveFilename); if (!saveFilename.equals(oldSave)) { JConfig.setConfiguration("savefile", saveFilename); } // If we already have a save file, preserve its name, and write // the new one to '.temp'. if (swapFiles) { newSave = saveFilename + ".temp"; File newSaveFile = new File(newSave); if (newSaveFile.exists()) newSaveFile.delete(); } StringBuffer buf = buildSaveBuffer(auctionsData, null); boolean saveDone = true; // Dump the save file out! try { PrintStream ps = new PrintStream(new FileOutputStream(newSave)); ps.println(buf); ps.close(); } catch (IOException e) { JConfig.log().handleException("Failed to save auctions.", e); saveDone = false; } // If the save was complete, and we have to swap old/new files, // then [remove prior '.old' file if necessary], save current XML // as '.old', and move most recent save file to be just a normal // save file. if (saveDone && swapFiles) { preserveFiles(saveFilename); } return saveDone; }
public static void createFileFromTwoFiles( String inputFileName1, String inputFileName2, String outputFileName) throws IOException { /* * Won't work with multithreads as there is the posibility someone will * try to write to the screen or two different executions of this * function. */ PrintStream oldSystemOut = System.out; PrintStream ps = new PrintStream(outputFileName); System.setOut(ps); copyFileToTheStandardOutput(inputFileName1); copyFileToTheStandardOutput(inputFileName2); System.setOut(oldSystemOut); ps.close(); }
/** * Dumps the contents of the specified class to the specified directory. The file is named * dump_dir/[class].bcel. It contains a synopsis of the fields and methods followed by the jvm * code for each method. * * @param jc javaclass to dump * @param dump_dir directory in which to write the file */ public static void dump(JavaClass jc, File dump_dir) { try { dump_dir.mkdir(); File path = new File(dump_dir, jc.getClassName() + ".bcel"); PrintStream p = new PrintStream(path); // Print the class, super class and interfaces p.printf("class %s extends %s\n", jc.getClassName(), jc.getSuperclassName()); String[] inames = jc.getInterfaceNames(); if ((inames != null) && (inames.length > 0)) { p.printf(" "); for (String iname : inames) p.printf("implements %s ", iname); p.printf("\n"); } // Print each field p.printf("\nFields\n"); for (Field f : jc.getFields()) p.printf(" %s\n", f); // Print the signature of each method p.printf("\nMethods\n"); for (Method m : jc.getMethods()) p.printf(" %s\n", m); // If this is not an interface, print the code for each method if (!jc.isInterface()) { for (Method m : jc.getMethods()) { p.printf("\nMethod %s\n", m); Code code = m.getCode(); if (code != null) p.printf(" %s\n", code.toString().replace("\n", "\n ")); } } // Print the details of the constant pool. p.printf("Constant Pool:\n"); ConstantPool cp = jc.getConstantPool(); Constant[] constants = cp.getConstantPool(); for (int ii = 0; ii < constants.length; ii++) { p.printf(" %d %s\n", ii, constants[ii]); } p.close(); } catch (Exception e) { throw new Error("Unexpected error dumping javaclass", e); } }
protected static int run(String message, String[] commandArray, File outputFile) { PrintStream out = System.out; PrintStream err = System.err; PrintStream fileStream = null; try { outputFile.getParentFile().mkdirs(); fileStream = new PrintStream(new FileOutputStream(outputFile)); System.setErr(fileStream); System.setOut(fileStream); return run(message, commandArray); } catch (FileNotFoundException e) { return -1; } finally { System.setOut(out); System.setErr(err); if (fileStream != null) fileStream.close(); } }
public static void recordData(String inurl) throws Exception { // pr = new PrintStream(new FileOutputStream("http://en.wikipedia.org/wiki/HAProxy")); pr = System.out; long start = System.currentTimeMillis(); pr.println(inurl + "****************************************************************"); printList(cleanUrlText(TextUtils.HTMLText(inurl))); String urls = TextUtils.HTMLLinkString(inurl, inurl); String[] url = urls.split("\\s+"); HashSet<String> urlMap = new HashSet<String>(url.length); urlMap.add(inurl); for (String ur : url) { /* * if(!urlMap.contains(ur)){ pr.println(ur+"***************************************************************"); try{ * printList(cleanUrlText(TextUtils.HTMLText(ur))); }catch(Exception e){ System.out.println("Error with url :"+ ur); e.printStackTrace(); } * urlMap.add(ur); } */ } pr.println("Time elapsed" + (start - System.currentTimeMillis())); pr.close(); }
/** * Changes the output of all probes to the specified file. This method may be called multiple * times during the execution of the JVM. * * @param pathname the pathname of the output file. */ public static void setOutput(String pathname) { // open specified file PrintStream previous = outputStream; try { outputStream = new PrintStream(new FileOutputStream(pathname)); } catch (FileNotFoundException e) { // if file cannot be opened, output remains unchanged return; } // close previous output if not standard output if (previous != null && !previous.equals(System.out)) { previous.close(); } // print date and time Format format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); outputStream.println("Starting on " + format.format(new Date())); }
private void saveDataToFile(File file) { try { PrintStream out = new PrintStream(new FileOutputStream(file)); // Print header line out.print("Time"); for (Sequence seq : seqs) { out.print("," + seq.name); } out.println(); // Print data lines if (seqs.size() > 0 && seqs.get(0).size > 0) { for (int i = 0; i < seqs.get(0).size; i++) { double excelTime = toExcelTime(times.time(i)); out.print(String.format(Locale.ENGLISH, "%.6f", excelTime)); for (Sequence seq : seqs) { out.print("," + getFormattedValue(seq.value(i), false)); } out.println(); } } out.close(); JOptionPane.showMessageDialog( this, Resources.format( Messages.FILE_CHOOSER_SAVED_FILE, file.getAbsolutePath(), file.length())); } catch (IOException ex) { String msg = ex.getLocalizedMessage(); String path = file.getAbsolutePath(); if (msg.startsWith(path)) { msg = msg.substring(path.length()).trim(); } JOptionPane.showMessageDialog( this, Resources.format(Messages.FILE_CHOOSER_SAVE_FAILED_MESSAGE, path, msg), Messages.FILE_CHOOSER_SAVE_FAILED_TITLE, JOptionPane.ERROR_MESSAGE); } }
private void doExportTimeTree() { FileDialog dialog = new FileDialog(this, "Export Time Tree File...", FileDialog.SAVE); dialog.setVisible(true); if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); PrintStream ps = null; try { ps = new PrintStream(file); writeTimeTreeFile(ps); ps.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog( this, "Error writing tree file: " + ioe.getMessage(), "Export Error", JOptionPane.ERROR_MESSAGE); } } }
/** * Closes down connections to the underlying process. This method will be used only if the * supporting Java Native Interface library could not be loaded. */ private synchronized void pure_close(PrintStream out) { /* * Try to close this process for at least 30 seconds. */ for (int i = 0; i < 30; i++) { try { in.close(); err.close(); out.flush(); out.close(); } catch (IOException ioe) { } try { exit_code = p.waitFor(); p.destroy(); break; } catch (InterruptedException ie) { } try { Thread.sleep(1000); } catch (InterruptedException ie) { } } }
public static void createFileOfSquaresAndSqrs(String inputFileName, String outputFileName) throws IOException { FileInputStream inputStream; inputStream = new FileInputStream(inputFileName); PrintStream outputStream; outputStream = new PrintStream(outputFileName); Scanner s = new Scanner(inputStream); int n = s.nextInt(); outputStream.println("The number of integers: " + n); for (int i = 0; i < n; i++) { int number = s.nextInt(); outputStream.println("number = " + number); outputStream.println("sqrt(" + number + ")=" + Math.sqrt(number)); outputStream.println("square(" + number + ")=" + number * number); } s.close(); inputStream.close(); outputStream.close(); }