Example usage for java.io FilterOutputStream write

List of usage examples for java.io FilterOutputStream write

Introduction

In this page you can find the example usage for java.io FilterOutputStream write.

Prototype

@Override
public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes to this output stream.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    OutputStream os = new FileOutputStream("C://test.txt");
    FilterOutputStream fos = new FilterOutputStream(os);

    fos.write(65);

    // forces byte contents to written out to the stream
    fos.flush();/*from   ww  w .  j a v  a 2s .c om*/

    // create output streams
    FileInputStream fis = new FileInputStream("C://test.txt");

    // read byte
    int i = fis.read();

    // convert integer to characters
    char c = (char) i;

    System.out.print("Character read: " + c);
    fos.close();
    fis.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    OutputStream os = new FileOutputStream("C://test.txt");
    FilterOutputStream fos = new FilterOutputStream(os);

    // writes buffer to the output stream
    fos.write(65);

    // forces byte contents to written out to the stream
    fos.flush();/*from  w  w w. j a va2s  .  co  m*/

    // create input streams
    FileInputStream fis = new FileInputStream("C://test.txt");

    // get byte from the file
    int i = fis.read();

    // convert integer to character
    char c = (char) i;

    System.out.print("Character read: " + c);
    fos.close();
    fis.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    byte[] buffer = { 65, 66, 67, 68, 69 };
    int i = 0;//from w ww.  ja  v a  2s  .com

    OutputStream os = new FileOutputStream("C://test.txt");
    FilterOutputStream fos = new FilterOutputStream(os);

    // writes buffer to the output stream
    fos.write(buffer);

    // forces byte contents to written out to the stream
    fos.flush();

    // create input streams
    FileInputStream fis = new FileInputStream("C://test.txt");

    while ((i = fis.read()) != -1) {
        // converts integer to the character
        char c = (char) i;
        System.out.println("Character read: " + c);
    }
    fos.close();
    fis.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    // create input streams
    OutputStream os = new FileOutputStream("C://test.txt");
    FilterOutputStream fos = new FilterOutputStream(os);

    // releases any system resources associated with the stream
    fos.close();//from  www.ja  v  a 2 s.  com

    // writes byte to the output stream
    fos.write(65);

}

From source file:sit.web.client.HttpHelper.java

public HTTPResponse doHttpUrlConnectionRequest(URL url, String method, String contentType, byte[] payload,
        String unamePword64) throws MalformedURLException, ProtocolException, IOException, URISyntaxException {

    if (payload == null) { //make sure payload is initialized
        payload = new byte[0];
    }/*from   w  ww.  j a v a2  s  . c  o  m*/

    boolean isHTTPS = url.getProtocol().equalsIgnoreCase("https");
    HttpURLConnection connection;

    if (isHTTPS) {
        connection = (HttpsURLConnection) url.openConnection();
    } else {
        connection = (HttpURLConnection) url.openConnection();
    }

    connection.setRequestMethod(method);
    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("Content-Length", String.valueOf(payload.length));

    if (isHTTPS) {
        connection.setRequestProperty("Authorization", "Basic " + unamePword64);
    }

    Logger.getLogger(HttpHelper.class.getName()).log(Level.FINER,
            "trying to connect:\n" + method + " " + url + "\nhttps:" + isHTTPS + "\nContentType:" + contentType
                    + "\nContent-Length:" + String.valueOf(payload.length));

    connection.setDoInput(true);
    if (payload.length > 0) {
        // open up the output stream of the connection
        connection.setDoOutput(true);
        FilterOutputStream output = new FilterOutputStream(connection.getOutputStream());

        // write out the data
        output.write(payload);
        output.close();
    }

    HTTPResponse response = new HTTPResponse(method + " " + url.toString(), payload, Charset.defaultCharset()); //TODO forward charset ot this method

    response.code = connection.getResponseCode();
    response.message = connection.getResponseMessage();

    Logger.getLogger(HttpHelper.class.getName()).log(Level.FINE,
            "received response: " + response.message + " with code: " + response.code);

    if (response.code != 500) {
        byte[] buffer = new byte[20480];

        ByteBuilder bytes = new ByteBuilder();

        // get ready to read the response from the cgi script
        DataInputStream input = new DataInputStream(connection.getInputStream());
        boolean done = false;
        while (!done) {
            int readBytes = input.read(buffer);
            done = (readBytes == -1);

            if (!done) {
                bytes.append(buffer, readBytes);
            }
        }
        input.close();
        response.reply = bytes.toString(Charset.defaultCharset());
    }
    return response;
}

From source file:com.datatorrent.lib.io.fs.AbstractFileOutputOperator.java

/**
 * This method processes received tuples.
 * Tuples are written out to the appropriate files as determined by the getFileName method.
 * If the output port is connected incoming tuples are also converted and emitted on the appropriate output port.
 * @param tuple An incoming tuple which needs to be processed.
 *//*  w  w w . j a va2  s .c o m*/
protected void processTuple(INPUT tuple) {
    String fileName = getFileName(tuple);

    if (Strings.isNullOrEmpty(fileName)) {
        return;
    }

    try {
        FilterOutputStream fsOutput = streamsCache.get(fileName).getFilterStream();
        byte[] tupleBytes = getBytesForTuple(tuple);
        long start = System.currentTimeMillis();
        fsOutput.write(tupleBytes);
        totalWritingTime += System.currentTimeMillis() - start;
        totalBytesWritten += tupleBytes.length;
        MutableLong currentOffset = endOffsets.get(fileName);

        if (currentOffset == null) {
            currentOffset = new MutableLong(0);
            endOffsets.put(fileName, currentOffset);
        }

        currentOffset.add(tupleBytes.length);

        if (rotationWindows > 0) {
            getRotationState(fileName).notEmpty = true;
        }

        if (rollingFile && currentOffset.longValue() > maxLength) {
            LOG.debug("Rotating file {} {} {}", fileName, openPart.get(fileName), currentOffset.longValue());
            rotate(fileName);
        }

        MutableLong count = counts.get(fileName);
        if (count == null) {
            count = new MutableLong(0);
            counts.put(fileName, count);
        }

        count.add(1);
    } catch (IOException | ExecutionException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jboss.remoting.transport.http.HTTPServerInvoker.java

private boolean processRequest(FilterInputStream dataInput, FilterOutputStream dataOutput) {
    boolean keepAlive = true;
    try {/*from   w  w w .ja va  2s.co  m*/
        Object response = null;
        boolean isError = false;
        String requestContentType = null;
        String methodType = null;
        String path = null;
        String httpVersion = null;

        InvocationRequest request = null;

        try {

            // Need to parse the header to find Content-Type

            /**
             * Read the first line, as this will be the POST or GET, path, and HTTP version.
             * Then next comes the headers.  (key value seperated by a ': '
             * Then followed by an empty \r\n, which will be followed by the payload
             */
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int ch;
            while ((ch = dataInput.read()) >= 0) {
                buffer.write(ch);
                if (ch == '\n') {
                    break;
                }
            }

            byte[] firstLineRaw = buffer.toByteArray();
            buffer.close();
            // now need to backup and make sure the character before the \n was a \r
            if (firstLineRaw[firstLineRaw.length - 2] == '\r') {
                //Got our first line, now to set the variables
                String firstLine = new String(firstLineRaw).trim();
                int startIndex = 0;
                int endIndex = firstLine.indexOf(' ');
                methodType = firstLine.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                endIndex = firstLine.indexOf(' ', startIndex);
                path = firstLine.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                httpVersion = firstLine.substring(startIndex);
            } else {
                log.error("Error processing first line.  Should have ended in \r\n, but did not");
                throw new RuntimeException(
                        "Error processing HTTP request type.  First line of request is invalid.");
            }

            Map metadata = new HashMap();
            Header[] headers = HttpParser.parseHeaders(dataInput);
            for (int x = 0; x < headers.length; x++) {
                String headerName = headers[x].getName();
                String headerValue = headers[x].getValue();
                metadata.put(headerName, headerValue);
                // doing this instead of getting from map since ignores case
                if ("Content-Type".equalsIgnoreCase(headerName)) {
                    requestContentType = headers[x].getValue();
                }
            }

            metadata.put(HTTPMetadataConstants.METHODTYPE, methodType);
            metadata.put(HTTPMetadataConstants.PATH, path);
            metadata.put(HTTPMetadataConstants.HTTPVERSION, httpVersion);

            // checks to see if is Connection: close, which will deactivate keep alive.
            keepAlive = checkForConnecctionClose(headers);

            if (methodType.equals("OPTIONS")) {
                request = createNewInvocationRequest(metadata, null);
                response = invoke(request);

                Map responseMap = request.getReturnPayload();

                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = "200 OK";
                dataOutput.write(status.getBytes());
                String server = "\r\n" + "Server: JBoss Remoting HTTP Server/" + Version.VERSION;
                dataOutput.write(server.getBytes());
                String date = "\r\n" + "Date: " + new Date();
                dataOutput.write(date.getBytes());
                String contentLength = "\r\n" + "Content-Length: 0";
                dataOutput.write(contentLength.getBytes());

                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                String close = "\r\n" + "Connection: close";
                dataOutput.write(close.getBytes());

                // content seperator
                dataOutput.write(("\r\n" + "\r\n").getBytes());

                dataOutput.flush();

                //nothing more to do since do not need to call handler for this one
                return keepAlive;

            } else if (methodType.equals("GET") || methodType.equals("HEAD")) {
                request = createNewInvocationRequest(metadata, null);
            } else // must be POST or PUT
            {
                UnMarshaller unmarshaller = getUnMarshaller();
                Object obj = unmarshaller.read(dataInput, metadata);

                if (obj instanceof InvocationRequest) {
                    request = (InvocationRequest) obj;
                } else {
                    if (WebUtil.isBinary(requestContentType)) {
                        request = getInvocationRequest(metadata, obj);
                    } else {
                        request = createNewInvocationRequest(metadata, obj);
                    }
                }
            }

            try {
                // call transport on the subclass, get the result to handback
                response = invoke(request);
            } catch (Throwable ex) {
                log.debug("Error thrown calling invoke on server invoker.", ex);
                response = ex;
                isError = true;
            }
        } catch (Throwable thr) {
            log.debug("Error thrown processing request.  Probably error with processing headers.", thr);
            if (thr instanceof SocketException) {
                log.error("Error processing on socket.", thr);
                keepAlive = false;
                return keepAlive;
            } else if (thr instanceof Exception) {
                response = (Exception) thr;
            } else {
                response = new Exception(thr);
            }
            isError = true;
        }

        if (dataOutput != null) {

            Map responseMap = null;

            if (request != null) {
                responseMap = request.getReturnPayload();
            }

            if (response == null) {
                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = "204 No Content";
                if (responseMap != null) {
                    String handlerStatus = (String) responseMap.get(HTTPMetadataConstants.RESPONSE_CODE);
                    if (handlerStatus != null) {
                        status = handlerStatus;
                    }
                }
                dataOutput.write(status.getBytes());
                String contentType = "\r\n" + "Content-Type" + ": " + "text/html";
                dataOutput.write(contentType.getBytes());
                String contentLength = "\r\n" + "Content-Length" + ": " + 0;
                dataOutput.write(contentLength.getBytes());
                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                dataOutput.write(("\r\n" + "\r\n").getBytes());
                //dataOutput.write("NULL return".getBytes());
                dataOutput.flush();
            } else {
                dataOutput.write("HTTP/1.1 ".getBytes());
                String status = null;
                if (isError) {
                    status = "500 JBoss Remoting: Error occurred within target application.";
                } else {
                    status = "200 OK";
                    if (responseMap != null) {
                        String handlerStatus = (String) responseMap.get(HTTPMetadataConstants.RESPONSE_CODE);
                        if (handlerStatus != null) {
                            status = handlerStatus;
                        }
                    }
                }

                dataOutput.write(status.getBytes());

                // write return headers
                String contentType = "\r\n" + "Content-Type" + ": " + requestContentType;
                dataOutput.write(contentType.getBytes());
                int iContentLength = getContentLength(response);
                String contentLength = "\r\n" + "Content-Length" + ": " + iContentLength;
                dataOutput.write(contentLength.getBytes());

                if (responseMap != null) {
                    Set entries = responseMap.entrySet();
                    Iterator itr = entries.iterator();
                    while (itr.hasNext()) {
                        Map.Entry entry = (Map.Entry) itr.next();
                        String entryString = "\r\n" + entry.getKey() + ": " + entry.getValue();
                        dataOutput.write(entryString.getBytes());
                    }
                }

                // content seperator
                dataOutput.write(("\r\n" + "\r\n").getBytes());

                if (methodType != null && !methodType.equals("HEAD")) {
                    // write response
                    Marshaller marshaller = getMarshaller();
                    marshaller.write(response, dataOutput);
                }
            }
        } else {
            if (isError) {
                log.warn(
                        "Can not send error response due to output stream being null (due to previous error).");
            } else {
                log.error(
                        "Can not send response due to output stream being null (even though there was not a previous error encountered).");
            }
        }
    } catch (Exception e) {
        log.error("Error processing client request.", e);
        keepAlive = false;
    }

    return keepAlive;
}