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: AbstractHtmlPrinter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #2
Source File: COSOutputStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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: IO.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #4
Source File: VfsStreamsTests.java    From xodus with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: WebUtil.java    From smart-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 下载文件
 */
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 #6
Source File: ImgUtil.java    From QiQuYing with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: TLBotInlineMediaResult.java    From TelegramApi with MIT License 6 votes vote down vote up
@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 #8
Source File: TLDialog.java    From kotlogram with MIT License 6 votes vote down vote up
@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 #9
Source File: InOutUtil.java    From evosql with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: HelpDisplayer.java    From jeka with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: GoldenFileTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: Base16Codec.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: FullBackupExporter.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: CompressedStreamTools.java    From AIBot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Write the compound, gzipped, to the outputstream.
 */
public static void writeCompressed(NBTTagCompound par0NBTTagCompound,
		OutputStream par1OutputStream) throws IOException {
	DataOutputStream dataoutputstream = new DataOutputStream(
			new GZIPOutputStream(par1OutputStream));

	try {
		write(par0NBTTagCompound, dataoutputstream);
	} finally {
		dataoutputstream.close();
	}
}
 
Example #15
Source File: ChunkedCipherOutputStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPOIFSWriterEvent(POIFSWriterEvent event) {
    try {
        OutputStream os = event.getStream();

        // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data
        // encrypted within the EncryptedData field, not including the size of the StreamSize field.
        // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this
        // value, depending on the block size of the chosen encryption algorithm
        byte buf[] = new byte[LittleEndianConsts.LONG_SIZE];
        LittleEndian.putLong(buf, 0, pos);
        os.write(buf);

        FileInputStream fis = new FileInputStream(fileOut);
        try {
            IOUtils.copy(fis, os);
        } finally {
            fis.close();
        }

        os.close();

        if (!fileOut.delete()) {
            LOG.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);
        }
    } catch (IOException e) {
        throw new EncryptedDocumentException(e);
    }
}
 
Example #16
Source File: DemuxOutputStream.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Writes byte to stream associated with current thread.
 *
 * @param ch the byte to write to stream
 * @throws IOException if an error occurs
 */
@Override
public void write( int ch )
    throws IOException
{
    OutputStream output = m_streams.get();
    if( null != output )
    {
        output.write( ch );
    }
}
 
Example #17
Source File: TileCacheWriter.java    From recast4j with zlib License 5 votes vote down vote up
private void writeCacheParams(OutputStream stream, TileCacheParams params, ByteOrder order) throws IOException {
    for (int i = 0; i < 3; i++) {
        write(stream, params.orig[i], order);
    }
    write(stream, params.cs, order);
    write(stream, params.ch, order);
    write(stream, params.width, order);
    write(stream, params.height, order);
    write(stream, params.walkableHeight, order);
    write(stream, params.walkableRadius, order);
    write(stream, params.walkableClimb, order);
    write(stream, params.maxSimplificationError, order);
    write(stream, params.maxTiles, order);
    write(stream, params.maxObstacles, order);
}
 
Example #18
Source File: SaasUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static FileObject extractWadlFile(WadlSaas saas) throws IOException {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(saas.getUrl());
    if (in == null) {
        return null;
    }
    OutputStream out = null;
    FileObject wadlFile;
    try {
        FileObject dir = saas.getSaasFolder();
        FileObject catalogDir = dir.getFileObject("catalog"); // NOI18N
        if (catalogDir == null) {
            catalogDir = dir.createFolder(CATALOG);
        }
        String wadlFileName = deriveFileName(saas.getUrl());
        wadlFile = catalogDir.getFileObject(wadlFileName);
        if (wadlFile == null) {
            wadlFile = catalogDir.createData(wadlFileName);
        }
        out = wadlFile.getOutputStream();
        FileUtil.copy(in, out);
    } finally {
        in.close();
        if (out != null) {
            out.close();
        }
    }
    return wadlFile;
}
 
Example #19
Source File: IOUtils.java    From pixymeta-android with Eclipse Public License 1.0 5 votes vote down vote up
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 #20
Source File: XMLExporter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void save(Savable object, OutputStream f) throws IOException {
    try {
        //Initialize Document when saving so we don't retain state of previous exports
        this.domOut = new DOMOutputCapsule(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(), this);
        domOut.write(object, object.getClass().getName(), null);
        DOMSerializer serializer = new DOMSerializer();
        serializer.serialize(domOut.getDoc(), f);
        f.flush();
    } catch (ParserConfigurationException ex) {
        throw new IOException(ex);
    }
}
 
Example #21
Source File: DoubleEncodingAlgorithm.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void encodeToOutputStream(Object data, OutputStream s) throws IOException {
    if (!(data instanceof double[])) {
        throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.dataNotDouble"));
    }

    final double[] fdata = (double[])data;

    encodeToOutputStreamFromDoubleArray(fdata, s);
}
 
Example #22
Source File: TriangleMesh.java    From toxiclibs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #23
Source File: IonBinary.java    From ion-java with Apache License 2.0 5 votes vote down vote up
static public int writeIonInt(OutputStream userstream, long value, int len) throws IOException
{
    // we shouldn't be writing out 0's as an Ion int value
    if (value == 0) {
        assert len == 0;
        return len;  // aka 0
    }

    // figure out how many we have bytes we have to write out
    long mask = 0xffL;
    boolean is_negative = (value < 0);

    assert len == IonBinary.lenIonInt(value);

    if (is_negative) {
        value = -value;
        // note for Long.MIN_VALUE the negation returns
        // itself as a value, but that's also the correct
        // "positive" value to write out anyway, so it
        // all works out
    }

    // write the rest
    switch (len) {  // we already wrote 1 byte
    case 8: userstream.write((byte)((value >> (8*7)) & mask));
    case 7: userstream.write((byte)((value >> (8*6)) & mask));
    case 6: userstream.write((byte)((value >> (8*5)) & mask));
    case 5: userstream.write((byte)((value >> (8*4)) & mask));
    case 4: userstream.write((byte)((value >> (8*3)) & mask));
    case 3: userstream.write((byte)((value >> (8*2)) & mask));
    case 2: userstream.write((byte)((value >> (8*1)) & mask));
    case 1: userstream.write((byte)(value & mask));
    }

    return len;
}
 
Example #24
Source File: ImapRequestStreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void writeSignoff(OutputStream output, ImapSession session) {
    try {
        output.write(MAILBOX_DELETED_SIGNOFF);
    } catch (IOException e) {
        LOGGER.warn("Failed to write signoff");
        LOGGER.debug("Failed to write signoff:", e);
    }
}
 
Example #25
Source File: TGAssetBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void getOutputStream(TGBrowserCallBack<OutputStream> cb, TGBrowserElement element) {
	try {
		throw new TGBrowserException("No writable file system");
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #26
Source File: Backup.java    From zoocreeper with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
    BackupOptions options = new BackupOptions();
    CmdLineParser parser = new CmdLineParser(options);
    try {
        parser.parseArgument(args);
        if (options.help) {
            usage(parser, 0);
        }
    } catch (CmdLineException e) {
        if (!options.help) {
            System.err.println(e.getLocalizedMessage());
        }
        usage(parser, options.help ? 0 : 1);
    }
    if (options.verbose) {
        LoggingUtils.enableDebugLogging(Backup.class.getPackage().getName());
    }
    Backup backup = new Backup(options);
    OutputStream os;
    if ("-".equals(options.outputFile)) {
        os = System.out;
    } else {
        os = new BufferedOutputStream(new FileOutputStream(options.outputFile));
    }
    try {
        if (options.compress) {
            os = new GZIPOutputStream(os);
        }
        backup.backup(os);
    } finally {
        os.flush();
        Closeables.close(os, true);
    }
}
 
Example #27
Source File: GifEncoder.java    From Logisim with GNU General Public License v3.0 5 votes vote down vote up
void Write(OutputStream output) throws IOException {
	BitUtils.WriteWord(output, localScreenWidth_);
	BitUtils.WriteWord(output, localScreenHeight_);
	output.write(byte_);
	output.write(backgroundColorIndex_);
	output.write(pixelAspectRatio_);
}
 
Example #28
Source File: FlowFileV3Utilities.java    From constellation with Apache License 2.0 5 votes vote down vote up
private static void copy(final InputStream in, final OutputStream out) throws IOException {
    final byte[] buffer = new byte[65536];
    int len;
    while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
    }
}
 
Example #29
Source File: LinkHamp.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
public LinkHamp(InputStream is,
                OutputStream os)
{
  this(ServicesAmp.newManager().start(),
       "remote://",
       is, os);
}
 
Example #30
Source File: JsonLineSerializer.java    From tajo with Apache License 2.0 5 votes vote down vote up
@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;
}