Example usage for java.io FilterOutputStream flush

List of usage examples for java.io FilterOutputStream flush

Introduction

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

Prototype

@Override
public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out to the 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);/*  w  w  w. j a  va 2s .  co m*/

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

    // 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);//from w w w . jav  a 2 s  .c  om

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

    // 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;//ww w . j  ava2 s.co m

    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 {

    byte[] buffer = { 65, 66, 67, 68, 69 };
    int i = 0;/*from  www.  j a  va 2s  . c o m*/
    OutputStream os = new FileOutputStream("C://test.txt");
    FilterOutputStream fos = new FilterOutputStream(os);

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

    // 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:com.lizardtech.expresszip.model.Job.java

private void writeZipFile(File baseDir, File archive, List<String> files)
        throws FileNotFoundException, IOException {
    FilterOutputStream out = null;
    ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(archive));
    stream.setLevel(Deflater.DEFAULT_COMPRESSION);
    out = stream;//from   w  w  w  .java  2  s  . co  m

    byte data[] = new byte[18024];

    for (String f : files) {
        logger.info(String.format("Writing %s to ZIP archive %s", f, archive));
        ((ZipOutputStream) out).putNextEntry(new ZipEntry(f));

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(baseDir, f)));

        int len = 0;
        while ((len = in.read(data)) > 0) {
            out.write(data, 0, len);
        }

        out.flush();
        in.close();
    }

    out.close();
}

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

private boolean processRequest(FilterInputStream dataInput, FilterOutputStream dataOutput) {
    boolean keepAlive = true;
    try {//w w w.j a  v a 2s. c om
        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;
}