Java Code Examples for java.io.OutputStream#write()

The following examples show how to use java.io.OutputStream#write() . 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: PostOnDelete.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    String requestMethod = exchange.getRequestMethod();

    if (requestMethod.equalsIgnoreCase("DELETE")) {
        InputStream is = exchange.getRequestBody();

        int count = 0;
        while (is.read() != -1) {
            count++;
        }
        is.close();

        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        exchange.sendResponseHeaders((count == len) ? 200 : 400, 0);
        OutputStream os = exchange.getResponseBody();
        String str = "Hello from server!";
        os.write(str.getBytes());
        os.flush();
        os.close();
    }
}
 
Example 2
Source File: PooledDirectByteBuf.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException {
    checkIndex(index, length);
    if (length == 0) {
        return;
    }

    byte[] tmp = new byte[length];
    ByteBuffer tmpBuf;
    if (internal) {
        tmpBuf = internalNioBuffer();
    } else {
        tmpBuf = memory.duplicate();
    }
    tmpBuf.clear().position(idx(index));
    tmpBuf.get(tmp);
    out.write(tmp);
}
 
Example 3
Source File: NetscapeCertTypeExtension.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Write the extension to the DerOutputStream.
 *
 * @param out the DerOutputStream to write the extension to.
 * @exception IOException on encoding errors.
 */
public void encode(OutputStream out) throws IOException {
    DerOutputStream  tmp = new DerOutputStream();

    if (this.extensionValue == null) {
        this.extensionId = NetscapeCertType_Id;
        this.critical = true;
        encodeThis();
    }
    super.encode(tmp);
    out.write(tmp.toByteArray());
}
 
Example 4
Source File: SybaseIqBooleanFormatter.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Override
public void write(byte i, OutputStream os) throws IOException
{
    if (i == 0 || i == 1)
    {
        os.write(i);
    }
    else throwConversionError("byte");
}
 
Example 5
Source File: Streams.java    From Mars-Java with MIT License 5 votes vote down vote up
/**
 * Copies the contents of the given {@link InputStream}
 * to the given {@link OutputStream}.
 *
 * @param inputStream The input stream, which is being read.
 *   It is guaranteed, that {@link InputStream#close()} is called
 *   on the stream.
 * @param outputStream The output stream, to which data should
 *   be written. May be null, in which case the input streams
 *   contents are simply discarded.
 * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
 *   is called on the stream. False indicates, that only
 *   {@link OutputStream#flush()} should be called finally.
 * @param buffer Temporary buffer, which is to be used for
 *   copying data.
 * @return Number of bytes, which have been copied.
 * @throws IOException An I/O error occurred.
 */
public static long copy(InputStream inputStream,
        OutputStream outputStream, boolean closeOutputStream,
        byte[] buffer)
throws IOException {
    OutputStream out = outputStream;
    InputStream in = inputStream;
    try {
        long total = 0;
        for (;;) {
            int res = in.read(buffer);
            if (res == -1) {
                break;
            }
            if (res > 0) {
                total += res;
                if (out != null) {
                    out.write(buffer, 0, res);
                }
            }
        }
        if (out != null) {
            if (closeOutputStream) {
                out.close();
            } else {
                out.flush();
            }
            out = null;
        }
        in.close();
        in = null;
        return total;
    } finally {
        IOUtils.closeQuietly(in);
        if (closeOutputStream) {
            IOUtils.closeQuietly(out);
        }
    }
}
 
Example 6
Source File: LZWEncoder.java    From stynico with MIT License 5 votes vote down vote up
void flush_char(OutputStream outs) throws IOException
   {
if (a_count > 0)
{
    outs.write(a_count);
    outs.write(accum, 0, a_count);
    a_count = 0;
}
   }
 
Example 7
Source File: CertificateVersion.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertificateVersion period in DER form to the stream.
 *
 * @param out the OutputStream to marshal the contents to.
 * @exception IOException on errors.
 */
public void encode(OutputStream out) throws IOException {
    // Nothing for default
    if (version == V1) {
        return;
    }
    DerOutputStream tmp = new DerOutputStream();
    tmp.putInteger(version);

    DerOutputStream seq = new DerOutputStream();
    seq.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0),
              tmp);

    out.write(seq.toByteArray());
}
 
Example 8
Source File: JAXRSOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void writeResponseErrorMessage(Message message, OutputStream out,
                                       String name, Class<?> cls, MediaType ct) {
    message.put(Message.CONTENT_TYPE, "text/plain");
    message.put(Message.RESPONSE_CODE, 500);
    try {
        String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct);
        if (out != null) {
            out.write(errorMessage.getBytes(StandardCharsets.UTF_8));
        }
    } catch (IOException another) {
        // ignore
    }
}
 
Example 9
Source File: Part.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
/**
 * Write the content disposition header to the specified output stream
 *
 * @param out The output stream
 * @throws IOException If an IO problem occurs.
 */
protected void sendDispositionHeader(final OutputStream out) throws IOException {
    out.write(CONTENT_DISPOSITION_BYTES);
    out.write(QUOTE_BYTES);
    out.write(EncodingUtils.getAsciiBytes(getName()));
    out.write(QUOTE_BYTES);
}
 
Example 10
Source File: MultipartBatchHttpMessageConverter.java    From documentum-rest-client-java with Apache License 2.0 5 votes vote down vote up
private void writeHeaders(OutputStream os, HttpHeaders headers) throws IOException {
    for(Map.Entry<String, List<String>> entry : headers.entrySet()) {
        for(String value : entry.getValue()) {
            os.write(entry.getKey().getBytes("UTF-8"));
            os.write(':');
            os.write(' ');
            os.write(value.getBytes("UTF-8"));
            writeNewLine(os);
        }
    }
    writeNewLine(os);
}
 
Example 11
Source File: IOUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Transfers all bytes that can be read from <tt>in</tt> to <tt>out</tt>.
 *
 * @param in  The InputStream to read data from.
 * @param out The OutputStream to write data to.
 * @return The total number of bytes transfered.
 * @throws IOException
 */
public static final long transfer(InputStream in, OutputStream out) throws IOException {
	long totalBytes = 0;
	int bytesInBuf = 0;
	byte[] buf = new byte[4096];

	while ((bytesInBuf = in.read(buf)) != -1) {
		out.write(buf, 0, bytesInBuf);
		totalBytes += bytesInBuf;
	}

	return totalBytes;
}
 
Example 12
Source File: StreamingRetry.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
void test(String method) throws Exception {
    ss = new ServerSocket(0);
    ss.setSoTimeout(ACCEPT_TIMEOUT);
    int port = ss.getLocalPort();

    Thread otherThread = new Thread(this);
    otherThread.start();

    try {
        URL url = new URL("http://localhost:" + port + "/");
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoOutput(true);
        if (method != null)
            uc.setRequestMethod(method);
        uc.setChunkedStreamingMode(4096);
        OutputStream os = uc.getOutputStream();
        os.write("Hello there".getBytes());

        InputStream is = uc.getInputStream();
        is.close();
    } catch (IOException expected) {
        //expected.printStackTrace();
    } finally {
        ss.close();
        otherThread.join();
    }
}
 
Example 13
Source File: CramIndex.java    From cramtools with Apache License 2.0 5 votes vote down vote up
public void writeTo(OutputStream os) throws IOException {
	Collections.sort(entries, byStartDesc);
	for (Entry e : entries) {
		String string = e.toString();
		os.write(string.getBytes());
		os.write('\n');
	}
}
 
Example 14
Source File: BigJar.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void createLargeFile(OutputStream os, long minlength) throws IOException {
    byte[] buffer = new byte[BUFFER_LEN];
    long count = getCount(minlength);
    for (long i = 0; i < count; i++) {
        os.write(buffer);
    }
    os.flush();
}
 
Example 15
Source File: TestFileUtils.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Copies the specified InputStream to the specified destination file. If the destination file does not exist,
 * it is created.
 *
 * @param in The InputStream
 * @param dst The destination file name.
 * @throws IOException
 */
public static void copy(InputStream in, File dst) throws IOException
{
    if(in == null)
    {
        throw new IllegalArgumentException("Provided InputStream must not be null");
    }

    try
    {
        if (!dst.exists())
        {
            dst.createNewFile();
        }

        OutputStream out = new FileOutputStream(dst);
        
        try
        {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
            {
                out.write(buf, 0, len);
            }
        }
        finally
        {
            out.close();
        }
    }
    finally
    {
        in.close();
    }
}
 
Example 16
Source File: CBZip2OutputStream.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
private void sendMTFValues7(final int nSelectors) throws IOException {
    final Data dataShadow = this.data;
    final byte[][] len = dataShadow.sendMTFValues_len;
    final int[][] code = dataShadow.sendMTFValues_code;
    final OutputStream outShadow = this.out;
    final byte[] selector = dataShadow.selector;
    final char[] sfmap = dataShadow.sfmap;
    final int nMTFShadow = this.nMTF;

    int selCtr = 0;

    int bsLiveShadow = this.bsLive;
    int bsBuffShadow = this.bsBuff;

    for (int gs = 0; gs < nMTFShadow;) {
        final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1);
        final int selector_selCtr = selector[selCtr] & 0xff;
        final int[] code_selCtr = code[selector_selCtr];
        final byte[] len_selCtr = len[selector_selCtr];

        while (gs <= ge) {
            final int sfmap_i = sfmap[gs];

            //
            // inlined: bsW(len_selCtr[sfmap_i] & 0xff,
            // code_selCtr[sfmap_i]);
            //
            while (bsLiveShadow >= 8) {
                outShadow.write(bsBuffShadow >> 24);
                bsBuffShadow <<= 8;
                bsLiveShadow -= 8;
            }
            final int n = len_selCtr[sfmap_i] & 0xFF;
            bsBuffShadow |= code_selCtr[sfmap_i] << (32 - bsLiveShadow - n);
            bsLiveShadow += n;

            gs++;
        }

        gs = ge + 1;
        selCtr++;
    }

    this.bsBuff = bsBuffShadow;
    this.bsLive = bsLiveShadow;
}
 
Example 17
Source File: Base64Encoder.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private int decodeLastBlock(OutputStream out, char c1, char c2, char c3, char c4) 
    throws IOException
{
    byte    b1, b2, b3, b4;
    
    if (c3 == padding)
    {
        b1 = decodingTable[c1];
        b2 = decodingTable[c2];

        if ((b1 | b2) < 0)
        {
            throw new IOException("invalid characters encountered at end of base64 data");
        }

        out.write((b1 << 2) | (b2 >> 4));
        
        return 1;
    }
    else if (c4 == padding)
    {
        b1 = decodingTable[c1];
        b2 = decodingTable[c2];
        b3 = decodingTable[c3];

        if ((b1 | b2 | b3) < 0)
        {
            throw new IOException("invalid characters encountered at end of base64 data");
        }
        
        out.write((b1 << 2) | (b2 >> 4));
        out.write((b2 << 4) | (b3 >> 2));
        
        return 2;
    }
    else
    {
        b1 = decodingTable[c1];
        b2 = decodingTable[c2];
        b3 = decodingTable[c3];
        b4 = decodingTable[c4];

        if ((b1 | b2 | b3 | b4) < 0)
        {
            throw new IOException("invalid characters encountered at end of base64 data");
        }
        
        out.write((b1 << 2) | (b2 >> 4));
        out.write((b2 << 4) | (b3 >> 2));
        out.write((b3 << 6) | b4);
        
        return 3;
    } 
}
 
Example 18
Source File: ServicesUtil.java    From dubbo-plus with Apache License 2.0 4 votes vote down vote up
private static void writeServiceHead(OutputStream outputStream) throws IOException {
    outputStream.write(encodeBytes("<thead><tr><th>Service Type</th><th colspan='2'>Methods</th><th>Service Path</th><th>Group</th><th>Version</th></tr></thead>"));
}
 
Example 19
Source File: TransferFsImage.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private static void copyFileToStream(OutputStream out, File localfile,
    FileInputStream infile, DataTransferThrottler throttler,
    Canceler canceler) throws IOException {
  byte buf[] = new byte[HdfsConstants.IO_FILE_BUFFER_SIZE];
  try {
    CheckpointFaultInjector.getInstance()
        .aboutToSendFile(localfile);

    if (CheckpointFaultInjector.getInstance().
          shouldSendShortFile(localfile)) {
        // Test sending image shorter than localfile
        long len = localfile.length();
        buf = new byte[(int)Math.min(len/2, HdfsConstants.IO_FILE_BUFFER_SIZE)];
        // This will read at most half of the image
        // and the rest of the image will be sent over the wire
        infile.read(buf);
    }
    int num = 1;
    while (num > 0) {
      if (canceler != null && canceler.isCancelled()) {
        throw new SaveNamespaceCancelledException(
          canceler.getCancellationReason());
      }
      num = infile.read(buf);
      if (num <= 0) {
        break;
      }
      if (CheckpointFaultInjector.getInstance()
            .shouldCorruptAByte(localfile)) {
        // Simulate a corrupted byte on the wire
        LOG.warn("SIMULATING A CORRUPT BYTE IN IMAGE TRANSFER!");
        buf[0]++;
      }
      
      out.write(buf, 0, num);
      if (throttler != null) {
        throttler.throttle(num, canceler);
      }
    }
  } catch (EofException e) {
    LOG.info("Connection closed by client");
    out = null; // so we don't close in the finally
  } finally {
    if (out != null) {
      out.close();
    }
  }
}
 
Example 20
Source File: IOUtils.java    From dttv-android with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Writes chars from a <code>char[]</code> to bytes on an
 * <code>OutputStream</code> using the specified character encoding.
 * <p>
 * Character encoding names can be found at
 * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
 * <p>
 * This method uses {@link String#String(char[])} and
 * {@link String#getBytes(String)}.
 * 
 * @param data  the char array to write, do not modify during output,
 * null ignored
 * @param output  the <code>OutputStream</code> to write to
 * @param encoding  the encoding to use, null means platform default
 * @throws NullPointerException if output is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 */
public static void write(char[] data, OutputStream output, String encoding)
        throws IOException {
    if (data != null) {
        if (encoding == null) {
            write(data, output);
        } else {
            output.write(new String(data).getBytes(encoding));
        }
    }
}