public void save(OutputStream outStream, boolean sorted) throws IOException { if (!sorted) { save(outStream); return; } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8")); String aKey; Object aValue; TreeMap tm = new TreeMap(this); for (Iterator i = tm.keySet().iterator(); i.hasNext();) { aKey = (String) i.next(); aValue = get(aKey); out.write(aKey + " = " + aValue); out.newLine(); } out.flush(); out.close(); }
private void writeComment(OutputStream os, String comment) throws Exception { os.write(EXTENSION_INTRODUCER); os.write(COMMENT_EXTENSION_LABEL); byte[] commentBytes = comment.getBytes(); int numBlocks = commentBytes.length/0xff; int leftOver = commentBytes.length % 0xff; int offset = 0; if(numBlocks > 0) { for(int i = 0; i < numBlocks; i++) { os.write(0xff); os.write(commentBytes, offset, 0xff); offset += 0xff; } } if(leftOver > 0) { os.write(leftOver); os.write(commentBytes, offset, leftOver); } os.write(0); }
public void train() { try { InputStreamFactory modelStream = new MarkableFileInputStreamFactory( new File(getClass().getClassLoader().getResource(TRAIN_INPUT).getFile()) ); final ObjectStream<String> lineStream = new PlainTextByLineStream(modelStream, "UTF-8"); final ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream); final TrainingParameters mlParams = new TrainingParameters(); mlParams.put(TrainingParameters.ITERATIONS_PARAM, 5000); mlParams.put(TrainingParameters.CUTOFF_PARAM, 5); final DoccatModel model = DocumentCategorizerME.train("en", sampleStream, mlParams, new DoccatFactory()); final Path path = Paths.get(MODEL_OUTPUT); FileUtils.touch(path.toFile()); try (OutputStream modelOut = new BufferedOutputStream(new FileOutputStream(path.toString()))) { model.serialize(modelOut); } } catch (Exception e) { LOGGER.error("an error occurred while training the sentiment analysis model", e); throw new IllegalStateException(e); } }
/** * Saves a chart to a file in PNG format. This method allows you to pass * in a {@link ChartRenderingInfo} object, to collect information about the * chart dimensions/entities. You will need this info if you want to * create an HTML image map. * * @param file the file (<code>null</code> not permitted). * @param chart the chart (<code>null</code> not permitted). * @param width the image width. * @param height the image height. * @param info the chart rendering info (<code>null</code> permitted). * * @throws IOException if there are any I/O errors. */ public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height, ChartRenderingInfo info) throws IOException { if (file == null) { throw new IllegalArgumentException("Null 'file' argument."); } OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { ChartUtilities.writeChartAsPNG(out, chart, width, height, info); } finally { out.close(); } }
public void printCounts(OutputStream out, boolean deltas) { PrintStream pout = new PrintStream(out); Iterator<Key> j = countMap.keySet().iterator(); while (j.hasNext()) { Key key = j.next(); int count = countMap.get(key).intValue(); if (count != 0) { pout.print(key + ":\t"); if (deltas && count > 0) pout.print("+"); pout.println(count); } } pout.flush(); }
/** * Generates the necessary files for the forms upload to the SeaBioData repository */ private void dispatchSBDExport() throws IOException { SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE); if (!settings.contains(Utils.TAG_SBD_USERNAME)) { Toast.makeText(this, getString(R.string.sbd_username_missing_export), Toast.LENGTH_SHORT).show(); return; } HashMap<String, ArrayList<FormInstance>> groupedInstances = new HashMap<>(); for (FormInstance fi : currentItem.getLinkedForms()) { if (groupedInstances.containsKey(fi.getParent())) { groupedInstances.get(fi.getParent()).add(fi); continue; } ArrayList<FormInstance> newInstances = new ArrayList<>(); newInstances.add(fi); groupedInstances.put(fi.getParent(), newInstances); } for (String key : groupedInstances.keySet()) { FormExportItem exportItem = new FormExportItem(groupedInstances.get(key), settings.getString(Utils.TAG_SBD_USERNAME, "")); File file = new File(Environment.getExternalStorageDirectory() + File.separator + key + "_" + new Date().toString() + ".json"); if(file.createNewFile()) { OutputStream fo = new FileOutputStream(file); fo.write(new Gson().toJson(exportItem).getBytes()); fo.close(); } } Toast.makeText(getApplicationContext(), getString(R.string.sbd_dorms_exported_successfully), Toast.LENGTH_SHORT).show(); }
/** * Writes a stream of bytes representing an audio file of the specified file type * to the output stream provided. Some file types require that * the length be written into the file header; such files cannot be written from * start to finish unless the length is known in advance. An attempt * to write a file of such a type will fail with an IOException if the length in * the audio file type is <code>AudioSystem.NOT_SPECIFIED</code>. * * @param stream the audio input stream containing audio data to be * written to the file * @param fileType the kind of audio file to write * @param out the stream to which the file data should be written * @return the number of bytes written to the output stream * @throws IOException if an input/output exception occurs * @throws IllegalArgumentException if the file type is not supported by * the system * @see #isFileTypeSupported * @see #getAudioFileTypes */ public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { List providers = getAudioFileWriters(); int bytesWritten = 0; boolean flag = false; for(int i=0; i < providers.size(); i++) { AudioFileWriter writer = (AudioFileWriter) providers.get(i); try { bytesWritten = writer.write( stream, fileType, out ); // throws IOException flag = true; break; } catch (IllegalArgumentException e) { // thrown if this provider cannot write the sequence, try the next continue; } } if(!flag) { throw new IllegalArgumentException("could not write audio file: file type not supported: " + fileType); } else { return bytesWritten; } }
@Override public void writeTo(OutputStream out) throws IOException { // Begin the map/object/array/whatever exactly this is out.write(AmfType.MAP.getValue()); // Write the "array size" Util.writeUnsignedInt32(out, properties.size()); // Write key/value pairs in this object for (Map.Entry<String, AmfData> entry : properties.entrySet()) { // The key must be a STRING type, and thus the "type-definition" byte is implied (not included in message) AmfString.writeStringTo(out, entry.getKey(), true); entry.getValue().writeTo(out); } // End the object out.write(OBJECT_END_MARKER); }
private void saveXml( final OutputStream out) throws IOException { final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, ENCODING)); writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writer.println("<files-list>"); for (FileEntry entry: this) { if (entry.getFile().exists() && !entry.isMetaDataReady()) { entry.calculateMetaData(); } writer.println(" " + entry.toXml()); } writer.println("</files-list>"); writer.flush(); }
public void getImage(OutputStream outputStream, String plantId, String uploadID) { try { Document filterDoc = new Document(); filterDoc.append("id", plantId); filterDoc.append("uploadID", uploadID); Iterator<Document> iter = plantCollection.find(filterDoc).iterator(); Document plant = iter.next(); String filePath = plant.getString("photoLocation"); // String filePath = ".photos" + '/' + plantId + ".png"; File file = new File(filePath); try { BufferedImage photo = ImageIO.read(file); ImageIO.write(photo,"JPEG",outputStream); } catch (IIOException e) {} } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("Could not write some Images to disk, exiting."); } }
public OutputStream createDataStream() { if (absDataFile.exists()) { if (overwrite == false) { throw new ExporterException("Package data file " + absDataFile.getAbsolutePath() + " already exists."); } log("Warning: Overwriting existing package file " + absDataFile.getAbsolutePath()); absDataFile.delete(); } try { absDataFile.createNewFile(); absDataStream = new FileOutputStream(absDataFile); return absDataStream; } catch(IOException e) { throw new ExporterException("Failed to create package file " + absDataFile.getAbsolutePath() + " due to " + e.getMessage()); } }
/** * 执行shell命令 * * @param cmd */ private void execShellCmd(String cmd) { try { // 申请获取root权限,这一步很重要,不然会没有作用 Process process = Runtime.getRuntime().exec("su"); // 获取输出流 OutputStream outputStream = process.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream( outputStream); dataOutputStream.writeBytes(cmd); dataOutputStream.flush(); dataOutputStream.close(); outputStream.close(); } catch (Throwable t) { t.printStackTrace(); } }
public void testShowItIsPossibleToPassInBeansWrappedObject() throws Exception { FileObject root = FileUtil.createMemoryFileSystem().getRoot(); FileObject fo = FileUtil.createData(root, "simpleObject.txt"); OutputStream os = fo.getOutputStream(); String txt = "<#if (classInfo.getMethods().size() > 0) >The size is greater than 0.</#if>"; os.write(txt.getBytes()); os.close(); StringWriter w = new StringWriter(); Map<String,Object> parameters = Collections.<String,Object>singletonMap( "classInfo", BeansWrapper.getDefaultInstance().wrap(new ClassInfo()) ); apply(fo, w, parameters); assertEquals("The size is greater than 0.", w.toString()); }
void initContents(OutputStream out) throws IOException { for (int i = 0; i < size; i++) { out.write(byteBuf); } out.write(new byte[4]); // add the 4 byte pad out.flush(); }
@Override public synchronized OutputStream createCompressionStream( OutputStream downStream, Compressor compressor, int downStreamBufferSize) throws IOException { if (downStreamBufferSize > 0) { return new BufferedOutputStream(downStream, downStreamBufferSize); } return downStream; }
@Test public void testWriteAndRead() throws Exception { // Generate a random tag byte[] tag = TestUtils.getRandomBytes(TAG_LENGTH); // Generate two frames with random payloads byte[] payload1 = TestUtils.getRandomBytes(123); byte[] payload2 = TestUtils.getRandomBytes(321); // Write the tag and the frames ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamEncrypter encrypter = new TestStreamEncrypter(out, tag); OutputStream streamWriter = new StreamWriterImpl(encrypter); streamWriter.write(payload1); streamWriter.flush(); streamWriter.write(payload2); streamWriter.flush(); byte[] output = out.toByteArray(); assertEquals(TAG_LENGTH + STREAM_HEADER_LENGTH + FRAME_HEADER_LENGTH + payload1.length + MAC_LENGTH + FRAME_HEADER_LENGTH + payload2.length + MAC_LENGTH, output.length); // Read the tag back ByteArrayInputStream in = new ByteArrayInputStream(output); byte[] recoveredTag = new byte[tag.length]; read(in, recoveredTag); assertArrayEquals(tag, recoveredTag); // Read the frames back StreamDecrypter decrypter = new TestStreamDecrypter(in); InputStream streamReader = new StreamReaderImpl(decrypter); byte[] recoveredPayload1 = new byte[payload1.length]; read(streamReader, recoveredPayload1); assertArrayEquals(payload1, recoveredPayload1); byte[] recoveredPayload2 = new byte[payload2.length]; read(streamReader, recoveredPayload2); assertArrayEquals(payload2, recoveredPayload2); streamWriter.close(); streamReader.close(); }
/** * Returns an {@link java.io.OutputStream OutputStream} that can * be used for storing the contents of the file. * * @return An {@link java.io.OutputStream OutputStream} that can be used * for storing the contensts of the file. * * @exception IOException if an error occurs. */ public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; }
public Data transform(Data data, XMLCryptoContext xc, OutputStream os) throws TransformException { if (data == null) { throw new NullPointerException("data must not be null"); } if (os == null) { throw new NullPointerException("output stream must not be null"); } return transformIt(data, xc, os); }
@Override public void writeTo(OutputStream out) throws IOException, MessagingException { if (text != null) { byte[] bytes = text.getBytes(charset); if (MimeUtil.ENC_QUOTED_PRINTABLE.equalsIgnoreCase(encoding)) { writeSignSafeQuotedPrintable(out, bytes); } else if (MimeUtil.ENC_8BIT.equalsIgnoreCase(encoding)) { out.write(bytes); } else { throw new IllegalStateException("Cannot get size for encoding!"); } } }
@Override public ByteSource createSource(byte[] bytes) throws IOException { checkNotNull(bytes); File file = createFile(); OutputStream out = new FileOutputStream(file); try { out.write(bytes); } finally { out.close(); } return Files.asByteSource(file); }
/** * Saves current default values into <CODE>FILENAME</CODE> * @return true iff file was correctly saved */ public static boolean save() { boolean saved = false; try { OutputStream output = new FileOutputStream(new File(getWorkingPath(), FILENAME)); prop.store(output, "JMT Default parameters definition"); saved = true; output.close(); } catch (IOException e) { logger.error("Error while storing default values", e); } return saved; }
@Override public OutputStream outputStream() throws IOException { synchronized (this) { checkNotClosed(); return outputStream; } }
/** * Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p> * * Equivalent to <tt>walletToProto(wallet).writeTo(output);</tt> */ public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }
@Test public void givenOutputStreamSetup_whenLogExecutedOnMainThread_thenVerifyExpectedOutput() { // given OutputStream outputStream = LogTesterTestUtils.setupConsoleOutputStream(); // when LogTester.log(mLogType, mMessage); // then LogTesterTestUtils.assertOutput(outputStream, mExpectedOutput); }
public static void copyFile(File source, File target) throws IOException { try ( InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target)) { byte[] buf = new byte[1024]; int length; while ((length = in.read(buf)) > 0) { out.write(buf, 0, length); } } }
@Override public void writeTo( final Widget widget, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(String.format("(widget %s %s)", widget.getId(), widget.getValue()).getBytes(StandardCharsets.UTF_8)); }
/** * Copy the contents of the given InputStream to the given OutputStream. * Leaves both streams open when done. * * @param in * the InputStream to copy from * @param out * the OutputStream to copy to * @return the number of bytes copied * @throws IOException * in case of I/O errors */ public static int copy(InputStream in, OutputStream out) throws IOException { Assert.notNull(in, "No InputStream specified"); Assert.notNull(out, "No OutputStream specified"); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); return byteCount; }
@Test public void testWrite() throws Exception { final TransferStatus status = new TransferStatus(); final int length = 1048576; final byte[] content = RandomUtils.nextBytes(length); status.setLength(content.length); final Path home = new DefaultHomeFinderService(session).find(); final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()); cryptomator.create(session, null, new VaultCredentials("test")); session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator)); final CryptoWriteFeature<String> writer = new CryptoWriteFeature<String>(session, new DropboxWriteFeature(session), cryptomator); final Cryptor cryptor = cryptomator.getCryptor(); final FileHeader header = cryptor.fileHeaderCryptor().create(); status.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header)); status.setNonces(new RotatingNonceGenerator(cryptomator.numberOfChunks(content.length))); status.setChecksum(writer.checksum(test).compute(new ByteArrayInputStream(content), status)); final OutputStream out = writer.write(test, status, new DisabledConnectionCallback()); assertNotNull(out); new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out); out.close(); assertTrue(new CryptoFindFeature(session, new DropboxFindFeature(session), cryptomator).find(test)); assertEquals(content.length, new CryptoListService(session, session, cryptomator).list(test.getParent(), new DisabledListProgressListener()).get(test).attributes().getSize()); assertEquals(content.length, new CryptoWriteFeature<>(session, new DropboxWriteFeature(session, new DefaultFindFeature(session), new DefaultAttributesFinderFeature(session), 150000000L), cryptomator).append(test, status.getLength(), PathCache.empty()).size, 0L); assertEquals(content.length, new CryptoWriteFeature<>(session, new DropboxWriteFeature(session, new DropboxFindFeature(session), new DropboxAttributesFinderFeature(session), 150000000L), cryptomator).append(test, status.getLength(), PathCache.empty()).size, 0L); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length); final InputStream in = new CryptoReadFeature(session, new DropboxReadFeature(session), cryptomator).read(test, new TransferStatus().length(content.length), new DisabledConnectionCallback()); new StreamCopier(status, status).transfer(in, buffer); assertArrayEquals(content, buffer.toByteArray()); new CryptoDeleteFeature(session, new DropboxDeleteFeature(session), cryptomator).delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
/** * outputStream转string按编码 * * @param out 输出流 * @param charsetName 编码格式 * @return 字符串 */ public static String outputStream2String(OutputStream out, String charsetName) { if (out == null || StringUtils.isSpace(charsetName)) return null; try { return new String(outputStream2Bytes(out), charsetName); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
@Override public void write(OutputStream s) throws IOException { try { s.write(data); } catch (IOException e) { Logger.getLogger(ByteArrayOutputRepresentation.class.getCanonicalName()).fine("Caught OutputRepresentation:IOException: " + e.getMessage()); } }
public void save() { try { OutputStream os = new BufferedOutputStream(mContext.openFileOutput(FILE_NAME, 0), 8192); DataOutputStream out = new DataOutputStream(os); out.writeInt(LAST_VERSION); out.writeInt(mDeleteMode); out.writeInt(mMode == null ? Base.DECIMAL.getQuickSerializable() : mMode.getQuickSerializable()); mHistory.write(out); out.close(); } catch (IOException e) { Log.e(TAG, "Cannot save to disc", e); } }
/** * Repair a store by rolling back to the newest good version. * * @param fileName the file name */ private static void repair(String fileName, PrintWriter pw) { long version = Long.MAX_VALUE; OutputStream ignore = new OutputStream() { @Override public void write(int b) throws IOException { // ignore } }; while (version >= 0) { pw.println(version == Long.MAX_VALUE ? "Trying latest version" : ("Trying version " + version)); pw.flush(); version = rollback(fileName, version, new PrintWriter(ignore)); try { String error = info(fileName + ".temp", new PrintWriter(ignore)); if (error == null) { FilePath.get(fileName).moveTo(FilePath.get(fileName + ".back"), true); FilePath.get(fileName + ".temp").moveTo(FilePath.get(fileName), true); pw.println("Success"); break; } pw.println(" ... failed: " + error); } catch (Exception e) { pw.println("Fail: " + e.getMessage()); pw.flush(); } version--; } pw.flush(); }
/** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); }
@Override public void save(@NonNull final OutputStream _outputStream, @NonNull final Object _object, @NonNull final List<Class<?>> _asStringClasses) { try { log.debug("Saving json"); mapper.writerWithDefaultPrettyPrinter().writeValue(_outputStream, _object); } catch (IOException _e) { log.error("Error saving JSON", _e); } }
@Test public void hasImpl() { Assert.assertTrue(impls.hasImpl(File.class)); Assert.assertTrue(impls.hasImpl(InputStream.class)); Assert.assertTrue(impls.hasImpl(DrbNode.class)); Assert.assertTrue(impls.hasImpl(URL.class)); Assert.assertTrue(impls.hasImpl(DrbItem.class)); Assert.assertFalse(impls.hasImpl(DrbNodeSpi.class)); Assert.assertFalse(impls.hasImpl(OutputStream.class)); }
private void pipe(final InputStream in, final OutputStream out) throws IOException { lastReadTime = System.currentTimeMillis(); final byte[] buf = new byte[BUF_SIZE]; int len = 0; while (len >= 0) { try { if (len != 0) { out.write(buf, 0, len); out.flush(); } len = in.read(buf); lastReadTime = System.currentTimeMillis(); } catch (final InterruptedIOException iioe) { if (iddleTimeout == 0) { return;// Other thread interrupted us. } final long timeSinceRead = System.currentTimeMillis() - lastReadTime; if (timeSinceRead >= iddleTimeout - 1000) { return; } len = 0; } } }
public void buildExcel(HttpServletRequest req, HttpServletResponse resp,boolean withPage,boolean withSheet) throws IOException { String file=req.getParameter("_u"); file=decode(file); if(StringUtils.isBlank(file)){ throw new ReportComputeException("Report file can not be null."); } String fileName=req.getParameter("_n"); fileName=buildDownloadFileName(file, fileName, ".xlsx"); resp.setContentType("application/octet-stream;charset=ISO8859-1"); fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1"); resp.setHeader("Content-Disposition","attachment;filename=\"" + fileName + "\""); Map<String, Object> parameters = buildParameters(req); OutputStream outputStream=resp.getOutputStream(); if(file.equals(PREVIEW_KEY)){ ReportDefinition reportDefinition=(ReportDefinition)TempObjectCache.getObject(PREVIEW_KEY); if(reportDefinition==null){ throw new ReportDesignException("Report data has expired,can not do export excel."); } Report report=reportBuilder.buildReport(reportDefinition, parameters); if(withPage){ excelProducer.produceWithPaging(report, outputStream); }else if(withSheet){ excelProducer.produceWithSheet(report, outputStream); }else{ excelProducer.produce(report, outputStream); } }else{ ExportConfigure configure=new ExportConfigureImpl(file,parameters,outputStream); if(withPage){ exportManager.exportExcelWithPaging(configure); }else if(withSheet){ exportManager.exportExcelWithPagingSheet(configure); }else{ exportManager.exportExcel(configure); } } outputStream.flush(); outputStream.close(); }
@Override public void writeTo(final OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); final InputStream instream = getContent(); try { int l; final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } } finally { instream.close(); } }
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } }