java.io.OutputStream Java Examples
The following examples show how to use
java.io.OutputStream.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VfsStreamsTests.java From xodus with Apache License 2.0 | 6 votes |
@Test public void writeRandomAccessRead() throws IOException { final Transaction txn = env.beginTransaction(); final File file0 = vfs.createFile(txn, "file0"); final OutputStream outputStream = vfs.appendFile(txn, file0); outputStream.write((HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN).getBytes(UTF_8)); outputStream.close(); txn.flush(); InputStream inputStream = vfs.readFile(txn, file0, 0); Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream)); inputStream.close(); inputStream = vfs.readFile(txn, file0, 10); Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream)); inputStream.close(); inputStream = vfs.readFile(txn, file0, 20); Assert.assertEquals(HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream)); inputStream.close(); inputStream = vfs.readFile(txn, file0, 30); Assert.assertEquals(HOEGAARDEN, streamAsString(inputStream)); inputStream.close(); txn.abort(); }
Example #2
Source File: COSOutputStream.java From gcs with Mozilla Public License 2.0 | 6 votes |
/** * Creates a new COSOutputStream writes to an encoded COS stream. * * @param filters Filters to apply. * @param parameters Filter parameters. * @param output Encoded stream. * @param scratchFile Scratch file to use. * * @throws IOException If there was an error creating a temporary buffer */ COSOutputStream(List<Filter> filters, COSDictionary parameters, OutputStream output, ScratchFile scratchFile) throws IOException { super(output); this.filters = filters; this.parameters = parameters; this.scratchFile = scratchFile; if (filters.isEmpty()) { this.buffer = null; } else { this.buffer = scratchFile.createBuffer(); } }
Example #3
Source File: WebUtil.java From smart-framework with Apache License 2.0 | 6 votes |
/** * 下载文件 */ public static void downloadFile(HttpServletResponse response, String filePath) { try { String originalFileName = FilenameUtils.getName(filePath); String downloadedFileName = new String(originalFileName.getBytes("GBK"), "ISO8859_1"); // 防止中文乱码 response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadedFileName + "\""); InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath)); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); StreamUtil.copyStream(inputStream, outputStream); } catch (Exception e) { logger.error("下载文件出错!", e); throw new RuntimeException(e); } }
Example #4
Source File: ImgUtil.java From QiQuYing with Apache License 2.0 | 6 votes |
public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } is.close(); os.close(); } catch(Exception ex){ ex.printStackTrace(); } }
Example #5
Source File: TLBotInlineMediaResult.java From TelegramApi with MIT License | 6 votes |
@Override public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeInt(flags, stream); StreamingUtils.writeTLString(id, stream); StreamingUtils.writeTLString(type, stream); if ((flags & FLAG_PHOTO) != 0) { StreamingUtils.writeTLObject(photo, stream); } if ((flags & FLAG_DOCUMENT) != 0) { StreamingUtils.writeTLObject(photo, stream); } if ((flags & FLAG_TITLE) != 0) { StreamingUtils.writeTLString(title, stream); } if ((flags & FLAG_DESCRIPTION) != 0) { StreamingUtils.writeTLString(title, stream); } StreamingUtils.writeTLObject(sendMessage, stream); }
Example #6
Source File: InOutUtil.java From evosql with Apache License 2.0 | 6 votes |
/** * Implementation only supports unix line-end format and is suitable for * processing HTTP and other network protocol communications. Reads and writes * a line of data. Returns the number of bytes read/written. */ public static int readLine(InputStream in, OutputStream out) throws IOException { int count = 0; for (;;) { int b = in.read(); if (b == -1) { break; } count++; out.write(b); if (b == '\n') { break; } } return count; }
Example #7
Source File: Base16Codec.java From ph-commons with Apache License 2.0 | 6 votes |
public void encode (@Nonnull @WillNotClose final InputStream aDecodedIS, @Nonnull @WillNotClose final OutputStream aOS) { ValueEnforcer.notNull (aDecodedIS, "DecodedInputStream"); ValueEnforcer.notNull (aOS, "OutputStream"); try { int nByte; while ((nByte = aDecodedIS.read ()) != -1) { aOS.write (StringHelper.getHexChar ((nByte & 0xf0) >> 4)); aOS.write (StringHelper.getHexChar (nByte & 0x0f)); } } catch (final IOException ex) { throw new EncodeException ("Failed to encode Base16", ex); } }
Example #8
Source File: FullBackupExporter.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
private void write(@NonNull OutputStream out, @NonNull BackupProtos.BackupFrame frame) throws IOException { try { Conversions.intToByteArray(iv, 0, counter++); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cipherKey, "AES"), new IvParameterSpec(iv)); byte[] frameCiphertext = cipher.doFinal(frame.toByteArray()); byte[] frameMac = mac.doFinal(frameCiphertext); byte[] length = Conversions.intToByteArray(frameCiphertext.length + 10); out.write(length); out.write(frameCiphertext); out.write(frameMac, 0, 10); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { throw new AssertionError(e); } }
Example #9
Source File: AbstractHtmlPrinter.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
protected WriterService createWriterService( final OutputStream out ) throws UnsupportedEncodingException { final String encoding = configuration.getConfigProperty( HtmlTableModule.ENCODING, EncodingRegistry.getPlatformDefaultEncoding() ); if ( isCreateBodyFragment() == false ) { if ( isInlineStylesRequested() ) { return WriterService.createPassThroughService( out, encoding ); } else { if ( isExternalStyleSheetRequested() && isForceBufferedWriting() == false ) { return WriterService.createPassThroughService( out, encoding ); } else { return WriterService.createBufferedService( out, encoding ); } } } else { return WriterService.createPassThroughService( out, encoding ); } }
Example #10
Source File: GoldenFileTestBase.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected void setUp() throws Exception { super.setUp(); File dataDir = getDataDir(); fname = getName().replace("test", ""); File f = new File(dataDir, getClass().getName(). replaceAll("\\.", "/") + "/" + fname + ".fxml"); File w = new File(getWorkDir(), f.getName()); InputStream is = new FileInputStream(f); OutputStream os = new FileOutputStream(w); FileUtil.copy(is, os); os.close(); is.close(); FileObject fo = FileUtil.toFileObject(w); sourceDO = DataObject.find(fo); document = ((EditorCookie)sourceDO.getCookie(EditorCookie.class)).openDocument(); hierarchy = TokenHierarchy.get(document); }
Example #11
Source File: HelpDisplayer.java From jeka with Apache License 2.0 | 6 votes |
static void help(JkCommandSet run, Path xmlFile) { final Document document = JkUtilsXml.createDocument(); final Element runEl = RunClassDef.of(run).toElement(document); document.appendChild(runEl); if (xmlFile == null) { JkUtilsXml.output(document, System.out); } else { JkUtilsPath.createFile(xmlFile); try (final OutputStream os = Files.newOutputStream(xmlFile)) { JkUtilsXml.output(document, os); } catch (final IOException e) { throw JkUtilsThrowable.unchecked(e); } JkLog.info("Xml help file generated at " + xmlFile); } }
Example #12
Source File: TLDialog.java From kotlogram with MIT License | 6 votes |
@Override public void serializeBody(OutputStream stream) throws IOException { computeFlags(); writeInt(flags, stream); writeTLObject(peer, stream); writeInt(topMessage, stream); writeInt(readInboxMaxId, stream); writeInt(readOutboxMaxId, stream); writeInt(unreadCount, stream); writeTLObject(notifySettings, stream); if ((flags & 1) != 0) { if (pts == null) throwNullFieldException("pts", flags); writeInt(pts, stream); } if ((flags & 2) != 0) { if (draft == null) throwNullFieldException("draft", flags); writeTLObject(draft, stream); } }
Example #13
Source File: IO.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
public static long copy(@WillNotClose InputStream in, @WillNotClose OutputStream out, long maxBytes) throws IOException { long total = 0; int sz = 0; byte buf[] = myByteBuf.get(); while (maxBytes > 0 && (sz = in.read(buf, 0, (int) Math.min(maxBytes, buf.length))) > 0) { total += sz; maxBytes -= sz; out.write(buf, 0, sz); } return total; }
Example #14
Source File: JsonLineSerializer.java From tajo with Apache License 2.0 | 5 votes |
@Override public int serialize(OutputStream out, Tuple input) throws IOException { JSONObject jsonObject = new JSONObject(); for (int i = 0; i < projectedPaths.length; i++) { String [] paths = projectedPaths[i].split(NestedPathUtil.PATH_DELIMITER); putValue(jsonObject, paths[0], paths, 0, i, input); } String jsonStr = jsonObject.toJSONString(); byte [] jsonBytes = jsonStr.getBytes(TextDatum.DEFAULT_CHARSET); out.write(jsonBytes); return jsonBytes.length; }
Example #15
Source File: TriangleMesh.java From toxiclibs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Saves the mesh as OBJ format to the given {@link OutputStream}. Currently * no texture coordinates are supported or written. * * @param stream */ public void saveAsOBJ(OutputStream stream) { OBJWriter obj = new OBJWriter(); obj.beginSave(stream); saveAsOBJ(obj); obj.endSave(); }
Example #16
Source File: TGAssetBrowser.java From tuxguitar with GNU Lesser General Public License v2.1 | 5 votes |
public void getOutputStream(TGBrowserCallBack<OutputStream> cb, TGBrowserElement element) { try { throw new TGBrowserException("No writable file system"); } catch (Throwable e) { cb.handleError(e); } }
Example #17
Source File: IOUtils.java From pixymeta-android with Eclipse Public License 1.0 | 5 votes |
public static void writeIntMM(OutputStream os, int value) throws IOException { os.write(new byte[] { (byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value}); }
Example #18
Source File: LinkHamp.java From baratine with GNU General Public License v2.0 | 5 votes |
public LinkHamp(InputStream is, OutputStream os) { this(ServicesAmp.newManager().start(), "remote://", is, os); }
Example #19
Source File: ExternalFileConfigurationEditor.java From eclipse-cs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Helper method trying to ensure that the file location provided by the user * exists. If that is not the case it prompts the user if an empty * configuration file should be created. * * @param location * the configuration file location * @throws CheckstylePluginException * error when trying to ensure the location file existance */ private boolean ensureFileExists(String location) throws CheckstylePluginException { // support dynamic location strings String resolvedLocation = ExternalFileConfigurationType.resolveDynamicLocation(location); File file = new File(resolvedLocation); if (!file.exists()) { boolean confirm = MessageDialog.openQuestion(mBtnBrowse.getShell(), Messages.ExternalFileConfigurationEditor_titleFileDoesNotExist, Messages.ExternalFileConfigurationEditor_msgFileDoesNotExist); if (confirm) { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { ConfigurationWriter.writeNewConfiguration(out, mWorkingCopy); } catch (IOException ioe) { CheckstylePluginException.rethrow(ioe); } return true; } return false; } return true; }
Example #20
Source File: DiskBasedCache.java From pearl with Apache License 2.0 | 5 votes |
static void writeLong(OutputStream os, long n) throws IOException { os.write((byte)(n >>> 0)); os.write((byte)(n >>> 8)); os.write((byte)(n >>> 16)); os.write((byte)(n >>> 24)); os.write((byte)(n >>> 32)); os.write((byte)(n >>> 40)); os.write((byte)(n >>> 48)); os.write((byte)(n >>> 56)); }
Example #21
Source File: LowLevelText.java From pdfbox-layout with MIT License | 5 votes |
public static void main(String[] args) throws Exception { final PDDocument test = new PDDocument(); final PDPage page = new PDPage(Constants.A4); float pageWidth = page.getMediaBox().getWidth(); float pageHeight = page.getMediaBox().getHeight(); test.addPage(page); final PDPageContentStream contentStream = new PDPageContentStream(test, page, true, true); // AnnotationDrawListener is only needed if you use annoation based stuff, e.g. hyperlinks AnnotationDrawListener annotationDrawListener = new AnnotationDrawListener(new DrawContext() { @Override public PDDocument getPdDocument() { return test; } @Override public PDPage getCurrentPage() { return page; } @Override public PDPageContentStream getCurrentPageContentStream() { return contentStream; } }); annotationDrawListener.beforePage(null); TextFlow text = TextFlowUtil .createTextFlowFromMarkup( "Hello *bold _italic bold-end* italic-end_. Eirmod\ntempor invidunt ut \\*labore", 11, BaseFont.Times); text.addText("Spongebob", 11, PDType1Font.COURIER); text.addText(" is ", 20, PDType1Font.HELVETICA_BOLD_OBLIQUE); text.addText("cool", 7, PDType1Font.HELVETICA); text.setMaxWidth(100); float xOffset = TextSequenceUtil.getOffset(text, pageWidth, Alignment.Right); text.drawText(contentStream, new Position(xOffset, pageHeight - 50), Alignment.Right, annotationDrawListener); String textBlock = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " + "{link[https://github.com/ralfstuckert/pdfbox-layout/]}pdfbox layout{link} " + "sed diam nonumy eirmod invidunt ut labore et dolore magna " + "aliquyam erat, _sed diam_ voluptua. At vero eos et *accusam et justo* " + "duo dolores et ea rebum.\n\nStet clita kasd gubergren, no sea takimata " + "sanctus est *Lorem ipsum _dolor* sit_ amet. Lorem ipsum dolor sit amet, " + "consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt " + "ut labore et dolore magna aliquyam erat, *sed diam voluptua.\n\n" + "At vero eos et accusam* et justo duo dolores et ea rebum. Stet clita kasd " + "gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n"; text = new TextFlow(); text.addMarkup(textBlock, 8, BaseFont.Courier); text.setMaxWidth(200); xOffset = TextSequenceUtil.getOffset(text, pageWidth, Alignment.Center); text.drawText(contentStream, new Position(xOffset, pageHeight - 100), Alignment.Justify, annotationDrawListener); // draw a round rect box with text text.setMaxWidth(350); float x = 50; float y = pageHeight - 300; float paddingX = 20; float paddingY = 15; float boxWidth = text.getWidth() + 2 * paddingX; float boxHeight = text.getHeight() + 2 * paddingY; Shape shape = new RoundRect(20); shape.fill(test, contentStream, new Position(x, y), boxWidth, boxHeight, Color.pink, null); shape.draw(test, contentStream, new Position(x, y), boxWidth, boxHeight, Color.blue, new Stroke(3), null); // now the text text.drawText(contentStream, new Position(x + paddingX, y - paddingY), Alignment.Center, annotationDrawListener); annotationDrawListener.afterPage(null); contentStream.close(); annotationDrawListener.afterRender(); final OutputStream outputStream = new FileOutputStream( "lowleveltext.pdf"); test.save(outputStream); test.close(); }
Example #22
Source File: TcpDiscoveryCoordinatorFailureTest.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override protected void writeToSocket( ClusterNode node, Socket sock, OutputStream out, TcpDiscoveryAbstractMessage msg, long timeout ) throws IOException, IgniteCheckedException { if (isDrop(msg)) return; super.writeToSocket(node, sock, out, msg, timeout); }
Example #23
Source File: SchemaRecordWriter.java From localization_nifi with Apache License 2.0 | 5 votes |
private void writeRecordFields(final Record record, final RecordSchema schema, final OutputStream out) throws IOException { final DataOutputStream dos = out instanceof DataOutputStream ? (DataOutputStream) out : new DataOutputStream(out); for (final RecordField field : schema.getFields()) { final Object value = record.getFieldValue(field); try { writeFieldRepetitionAndValue(field, value, dos); } catch (final Exception e) { throw new IOException("Failed to write field '" + field.getFieldName() + "'", e); } } }
Example #24
Source File: AnnoCommentTest.java From xlsmapper with Apache License 2.0 | 5 votes |
/** * 書込みのテスト - メソッドにアノテーションを付与 */ @Test public void test_save_comment_method_anno() throws Exception { // テストデータの作成 final MethodAnnoSheet outSheet = new MethodAnnoSheet(); outSheet.comment1("コメント1") .comment2("コメント2"); // ファイルへの書き込み XlsMapper mapper = new XlsMapper(); mapper.getConfiguration().setContinueTypeBindFailure(true); File outFile = new File(OUT_DIR, outFilename); try(InputStream template = new FileInputStream(templateFile); OutputStream out = new FileOutputStream(outFile)) { mapper.save(template, out, outSheet); } // 書き込んだファイルを読み込み値の検証を行う。 try(InputStream in = new FileInputStream(outFile)) { SheetBindingErrors<MethodAnnoSheet> errors = mapper.loadDetail(in, MethodAnnoSheet.class); MethodAnnoSheet sheet = errors.getTarget(); assertThat(sheet.comment1Position).isEqualTo(CellPosition.of("B3")); assertThat(sheet.comment2Position).isEqualTo(CellPosition.of("C5")); assertThat(sheet.labels).isNull(); assertThat(sheet.comments).isNull(); assertThat(sheet.comment1).isEqualTo(outSheet.comment1); assertThat(sheet.comment2).isEqualTo(outSheet.comment2); } }
Example #25
Source File: OcrInitAsyncTask.java From android-mrz-reader with Apache License 2.0 | 5 votes |
private boolean copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } return true; }
Example #26
Source File: ProfilesManager.java From Aria2App with GNU General Public License v3.0 | 5 votes |
public void save(@NonNull MultiProfile profile) throws IOException, JSONException { File file = new File(profilesPath, profile.id + ".profile"); try (OutputStream out = new FileOutputStream(file)) { out.write(profile.toJson().toString().getBytes()); out.flush(); } }
Example #27
Source File: QlikAppMessageBodyGenerator.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public void writeTo(DatasetConfig dataset, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { List<ViewFieldType> viewFieldTypes = ViewFieldsHelper.getViewFields(dataset); ImmutableListMultimap<QlikFieldType, ViewFieldType> mapping = FluentIterable.from(viewFieldTypes).index(FIELD_TO_QLIKTYPE); DatasetPath datasetPath = new DatasetPath(dataset.getFullPathList()); // qlik doesn't like certain characters as an identifier, so lets remove them String sanitizedDatasetName = dataset.getName().replaceAll("["+ Pattern.quote("/!@ *-=+{}<>,~")+"]+", "_"); try (PrintWriter pw = new PrintWriter(entityStream)) { pw.println("SET DirectIdentifierQuoteChar='" + QUOTE + "';"); pw.println(); pw.println("LIB CONNECT TO 'Dremio';"); pw.println(); // Create a resident load so that data can be referenced later pw.format("%s: DIRECT QUERY\n", sanitizedDatasetName); for(Map.Entry<QlikFieldType, Collection<ViewFieldType>> entry: mapping.asMap().entrySet()) { writeFields(pw, entry.getKey().name(), entry.getValue()); } /* Qlik supports paths with more than 2 components ("foo"."bar"."baz"."boo"), but each individual path segment * must be quoted to work with Dremio. SqlUtils.quoteIdentifier will only quote when needed, so we do another * pass to ensure they are quoted. */ final List<String> quotedPathComponents = Lists.newArrayList(); for (final String component : dataset.getFullPathList()) { String quoted = SqlUtils.quoteIdentifier(component); if (!quoted.startsWith(String.valueOf(SqlUtils.QUOTE)) || !quoted.endsWith(String.valueOf(SqlUtils.QUOTE))) { quoted = quoteString(quoted); } quotedPathComponents.add(quoted); } pw.format(" FROM %1$s;\n", Joiner.on('.').join(quotedPathComponents)); } }
Example #28
Source File: P11KeyStore.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * engineStore currently is a No-op. * Entries are stored to the token during engineSetEntry * * @param stream this must be <code>null</code> * @param password this must be <code>null</code> */ public synchronized void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { token.ensureValid(); if (stream != null && !token.config.getKeyStoreCompatibilityMode()) { throw new IOException("output stream must be null"); } if (password != null && !token.config.getKeyStoreCompatibilityMode()) { throw new IOException("password must be null"); } }
Example #29
Source File: RunJar.java From hadoop with Apache License 2.0 | 5 votes |
/** * Unpack matching files from a jar. Entries inside the jar that do * not match the given pattern will be skipped. * * @param jarFile the .jar file to unpack * @param toDir the destination directory into which to unpack the jar * @param unpackRegex the pattern to match jar entries against */ public static void unJar(File jarFile, File toDir, Pattern unpackRegex) throws IOException { JarFile jar = new JarFile(jarFile); try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (!entry.isDirectory() && unpackRegex.matcher(entry.getName()).matches()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, entry.getName()); ensureDirectory(file.getParentFile()); OutputStream out = new FileOutputStream(file); try { IOUtils.copyBytes(in, out, 8192); } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } }
Example #30
Source File: GifEncoder.java From Logisim with GNU General Public License v3.0 | 5 votes |
void Write(OutputStream output) throws IOException { BitUtils.WriteWord(output, localScreenWidth_); BitUtils.WriteWord(output, localScreenHeight_); output.write(byte_); output.write(backgroundColorIndex_); output.write(pixelAspectRatio_); }