List of usage examples for java.io PrintStream close
public void close()
From source file:com.genentech.chemistry.openEye.apps.SDFCatsIndexer.java
private void printDescriptors(String inFile, String outFile) throws FileNotFoundException { oemolithread ifs = new oemolithread(inFile); PrintStream out; if (".tab".equals(outFile)) out = System.out;// ww w. j a v a 2s . c o m else out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFile))); long start = System.currentTimeMillis(); int iCounter = 0; //Structures in the SD file. indexer.printDescriptorHeader(out); OEMolBase mol = new OEGraphMol(); while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; indexer.printDistanceDescriptors(out, mol); //Output "." to show that the program is running. if (iCounter % 100 == 0) System.err.print("."); if (iCounter % 4000 == 0) { System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000); } } mol.delete(); out.close(); ifs.close(); ifs.delete(); inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), ""); System.err.printf("%s: Read %d structures from %s. in %d sec\n", MY_NAME, iCounter, inFile, (System.currentTimeMillis() - start) / 1000); }
From source file:com.juick.android.Utils.java
public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) { try {//from ww w .j av a2 s .co m final String end = "\r\n"; final String twoHyphens = "--"; final String boundary = "****+++++******+++++++********"; URL apiUrl = new URL(url); final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setConnectTimeout(10000); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.connect(); OutputStream out = conn.getOutputStream(); PrintStream ps = new PrintStream(out); int index = 0; byte[] block = new byte[1024]; for (NameValuePair nameValuePair : data) { ps.print(twoHyphens + boundary + end); ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end); final InputStream value = nameValuePair.getValue(); while (true) { final int rd = value.read(block, 0, block.length); if (rd < 1) { break; } ps.write(block, 0, rd); } value.close(); ps.print(end); } ps.print(twoHyphens + boundary + twoHyphens + end); ps.close(); boolean b = conn.getResponseCode() == 200; if (!b) { return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false, null); } else { InputStream inputStream = conn.getInputStream(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; while (true) { int rd = inputStream.read(arr); if (rd < 1) break; baos.write(arr, 0, rd); } if (conn.getHeaderField("X-GZIPCompress") != null) { return new RESTResponse(null, false, baos.toString(0)); } else { return new RESTResponse(null, false, baos.toString()); } } finally { inputStream.close(); } } } catch (IOException e) { return new RESTResponse(e.toString(), false, null); } }
From source file:fr.cs.examples.propagation.TrackCorridor.java
private void run(final File input, final File output, final String separator) throws IOException, IllegalArgumentException, OrekitException { // read input parameters KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class); parser.parseInput(new FileInputStream(input)); TimeScale utc = TimeScalesFactory.getUTC(); Propagator propagator;//w w w.j av a 2 s . c o m if (parser.containsKey(ParameterKey.TLE_LINE1)) { propagator = createPropagator(parser.getString(ParameterKey.TLE_LINE1), parser.getString(ParameterKey.TLE_LINE2)); } else { propagator = createPropagator(parser.getDate(ParameterKey.ORBIT_CIRCULAR_DATE, utc), parser.getDouble(ParameterKey.ORBIT_CIRCULAR_A), parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EX), parser.getDouble(ParameterKey.ORBIT_CIRCULAR_EY), parser.getAngle(ParameterKey.ORBIT_CIRCULAR_I), parser.getAngle(ParameterKey.ORBIT_CIRCULAR_RAAN), parser.getAngle(ParameterKey.ORBIT_CIRCULAR_ALPHA)); } // simulation properties AbsoluteDate start = parser.getDate(ParameterKey.START_DATE, utc); double duration = parser.getDouble(ParameterKey.DURATION); double step = parser.getDouble(ParameterKey.STEP); double angle = parser.getAngle(ParameterKey.ANGULAR_OFFSET); // set up a handler to gather all corridor points CorridorHandler handler = new CorridorHandler(angle); propagator.setMasterMode(step, handler); // perform propagation, letting the step handler populate the corridor propagator.propagate(start, start.shiftedBy(duration)); // retrieve the built corridor List<CorridorPoint> corridor = handler.getCorridor(); // create a 7 columns csv file representing the corridor in the user home directory, with // date in column 1 (in ISO-8601 format) // left limit latitude in column 2 and left limit longitude in column 3 // center track latitude in column 4 and center track longitude in column 5 // right limit latitude in column 6 and right limit longitude in column 7 DecimalFormat format = new DecimalFormat("#00.00000", new DecimalFormatSymbols(Locale.US)); PrintStream stream = new PrintStream(output); for (CorridorPoint p : corridor) { stream.println(p.getDate() + separator + format.format(FastMath.toDegrees(p.getLeft().getLatitude())) + separator + format.format(FastMath.toDegrees(p.getLeft().getLongitude())) + separator + format.format(FastMath.toDegrees(p.getCenter().getLatitude())) + separator + format.format(FastMath.toDegrees(p.getCenter().getLongitude())) + separator + format.format(FastMath.toDegrees(p.getRight().getLatitude())) + separator + format.format(FastMath.toDegrees(p.getRight().getLongitude()))); } stream.close(); }
From source file:com.google.cloud.dataflow.sdk.runners.worker.TextReaderTest.java
@Test public void testCloneIteratorWithEndPositionAndFinalBytesInBuffer() throws Exception { String line = "a\n"; boolean stripNewlines = false; File tmpFile = tmpFolder.newFile(); List<String> expected = new ArrayList<>(); PrintStream writer = new PrintStream(new FileOutputStream(tmpFile)); // Write 5x the size of the buffer and 10 extra trailing bytes for (long bytesWritten = 0; bytesWritten < TextReader.BUF_SIZE * 3 + 10;) { writer.print(line);//from ww w . j a va2s . c o m expected.add(line); bytesWritten += line.length(); } writer.close(); Long fileSize = tmpFile.length(); TextReader<String> textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, fileSize, StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); List<String> actual = new ArrayList<>(); Reader.ReaderIterator<String> iterator = textReader.iterator(); while (iterator.hasNext()) { actual.add(iterator.next()); iterator = iterator.copy(); } assertEquals(expected, actual); }
From source file:org.apache.geode.internal.cache.BackupDUnitTest.java
private long setBackupFiles(final VM vm) { SerializableCallable setUserBackups = new SerializableCallable("set user backups") { public Object call() { final int pid = DUnitEnv.get().getPid(); File vmdir = new File("userbackup_" + pid); File test1 = new File(vmdir, "test1"); File test2 = new File(test1, "test2"); File mytext = new File(test2, "my.txt"); final ArrayList<File> backuplist = new ArrayList<>(); test2.mkdirs();//w w w. j a va2s . co m PrintStream ps = null; try { ps = new PrintStream(mytext); } catch (FileNotFoundException e) { fail(e.getMessage()); } ps.println(pid); ps.close(); mytext.setExecutable(true, true); long lastModified = mytext.lastModified(); backuplist.add(test2); Cache cache = getCache(); GemFireCacheImpl gfci = (GemFireCacheImpl) cache; gfci.setBackupFiles(backuplist); return lastModified; } }; return (long) vm.invoke(setUserBackups); }
From source file:org.csp.everyaware.internet.StoreAndForwardService.java
public static byte[] zipStringToBytes(String input) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); //BufferedOutputStream buffs = new BufferedOutputStream (new GZIPOutputStream (bos)); //use PrintStream to avod converting a String into byte array, that can cause out of memory error final PrintStream printStream = new PrintStream(new GZIPOutputStream(bos)); printStream.print(input);//from ww w . j a v a 2s . com printStream.close(); //buffs.write (input. getBytes ()); //buffs.close (); byte[] retval = bos.toByteArray(); bos.close(); return retval; }
From source file:cz.zcu.kiv.eegdatabase.logic.csv.SimpleCSVFactory.java
/** * Generating csv file from scenarios/*from w ww . jav a 2s . co m*/ * * @return csv file with scenarios * @throws IOException - error writing to stream */ @Transactional(readOnly = true) public OutputStream generateScenariosCsvFile() throws IOException { log.debug("Creating output stream"); OutputStream out = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(out); List<Scenario> scenarioList = scenarioDao.getAllRecords(); log.debug("Creating table header"); printStream.println( CSVUtils.SCENARIO_TITLE + CSVUtils.SEMICOLON + CSVUtils.SCENARIO_LENGTH + CSVUtils.SEMICOLON + CSVUtils.SCENARIO_DESCRIPTION + CSVUtils.SEMICOLON + CSVUtils.SCENARIO_DETAILS); log.debug("Printing experiments to outputstream"); for (int i = 0; i < scenarioList.size(); i++) { printStream.println(scenarioList.get(i).getTitle() + CSVUtils.SEMICOLON + scenarioList.get(i).getScenarioLength() + CSVUtils.SEMICOLON + scenarioList.get(i).getDescription() + CSVUtils.SEMICOLON + CSVUtils.PROTOCOL_HTTP + domain + CSVUtils.SCENARIO_URL + scenarioList.get(i).getScenarioId()); } printStream.close(); return out; }
From source file:org.apache.oodt.cas.filemgr.cli.action.TestIngestProductCliAction.java
private File createMetadataFile() throws IOException { File metadataFile = new File(tmpDir, "test.met"); metadataFile.deleteOnExit();/* w w w . j a v a2 s .com*/ PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream(metadataFile)); ps.println("<cas:metadata xmlns:cas=\"http://oodt.jpl.nasa.gov/1.0/cas\">"); ps.println(" <keyval type=\"scalar\">"); ps.println(" <key>" + FILENAME_MET_KEY + "</key>"); ps.println(" <val>" + FILENAME_MET_VAL + "</val>"); ps.println(" </keyval>"); ps.println(" <keyval type=\"scalar\">"); ps.println(" <key>" + NOMINAL_DATE_MET_KEY + "</key>"); ps.println(" <val>" + NOMINAL_DATE_MET_VAL + "</val>"); ps.println(" </keyval>"); ps.println("</cas:metadata>"); } finally { ps.close(); } return metadataFile; }
From source file:com.act.lcms.MS2.java
private void plot(MS2Collected Ams2Peaks, MS2Collected Bms2Peaks, Double mz, String outPrefix, String fmt) throws IOException { MS2Collected[] ms2Spectra = new MS2Collected[] { Ams2Peaks, Bms2Peaks }; String outPDF = outPrefix + "." + fmt; String outDATA = outPrefix + ".data"; // Write data output to outfile PrintStream out = new PrintStream(new FileOutputStream(outDATA)); List<String> plotID = new ArrayList<>(ms2Spectra.length); for (MS2Collected yzSlice : ms2Spectra) { plotID.add(String.format("time: %.4f, volts: %.4f", yzSlice.triggerTime, yzSlice.voltage)); // print out the spectra to outDATA for (YZ yz : yzSlice.ms2) { out.format("%.4f\t%.4f\n", yz.mz, yz.intensity); out.flush();/*from w w w . j a v a 2s . c o m*/ } // delimit this dataset from the rest out.print("\n\n"); } // close the .data out.close(); // render outDATA to outPDF using gnuplot // 105.0 here means 105% for the y-range of a [0%:100%] plot. We want to leave some buffer space at // at the top, and hence we go a little outside of the 100% max range. new Gnuplotter().plot2DImpulsesWithLabels(outDATA, outPDF, plotID.toArray(new String[plotID.size()]), mz + 50.0, "mz", 105.0, "intensity (%)", fmt); }
From source file:org.apache.hadoop.mapred.MRBench.java
/** * Generate a text file on the given filesystem with the given path name. * The text file will contain the given number of lines of generated data. * The generated data are string representations of numbers. Each line * is the same length, which is achieved by padding each number with * an appropriate number of leading '0' (zero) characters. The order of * generated data is one of ascending, descending, or random. *//* w w w .j a v a 2s .c o m*/ public void generateTextFile(FileSystem fs, Path inputFile, long numLines, Order sortOrder) throws IOException { LOG.info("creating control file: " + numLines + " numLines, " + sortOrder + " sortOrder"); PrintStream output = null; try { output = new PrintStream(fs.create(inputFile)); int padding = String.valueOf(numLines).length(); switch (sortOrder) { case RANDOM: for (long l = 0; l < numLines; l++) { output.println(pad((new Random()).nextLong(), padding)); } break; case ASCENDING: for (long l = 0; l < numLines; l++) { output.println(pad(l, padding)); } break; case DESCENDING: for (long l = numLines; l > 0; l--) { output.println(pad(l, padding)); } break; } } finally { if (output != null) output.close(); } LOG.info("created control file: " + inputFile); }