Utilities related to file and stream handling. : Stream « File Input Output « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » File Input Output » StreamScreenshots 
Utilities related to file and stream handling.
   
/*
    JSPWiki - a JSP-based WikiWiki clone.

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.   
 */


import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;


/**
 *  Generic utilities related to file and stream handling.
 */
// FIXME3.0: This class will move to "util" directory in 3.0
public final class FileUtil
{
    /** Size of the buffer used when copying large chunks of data. */
    private static final int      BUFFER_SIZE = 4096;

    /**
     *  Private constructor prevents instantiation.
     */
    private FileUtil()
    {}

    /**
     *  Makes a new temporary file and writes content into it. The temporary
     *  file is created using <code>File.createTempFile()</code>, and the usual
     *  semantics apply.  The files are not deleted automatically in exit.
     *
     *  @param content Initial content of the temporary file.
     *  @param encoding Encoding to use.
     *  @return The handle to the new temporary file
     *  @throws IOException If the content creation failed.
     *  @see java.io.File#createTempFile(String,String,File)
     */
    public static File newTmpFileString content, String encoding )
        throws IOException
    {
        Writer out = null;
        Reader in  = null;
        File   f   = null;

        try
        {
            f = File.createTempFile"jspwiki"null );

            in = new StringReadercontent );

            out = new OutputStreamWriternew FileOutputStream),
                                          encoding );

            copyContentsin, out );
        }
        finally
        {
            ifin  != null in.close();
            ifout != null out.close();
        }

        return f;
    }

    /**
     *  Creates a new temporary file using the default encoding
     *  of ISO-8859-1 (Latin1).
     *
     *  @param content The content to put into the file.
     *  @throws IOException If writing was unsuccessful.
     *  @return A handle to the newly created file.
     *  @see #newTmpFile( String, String )
     *  @see java.io.File#createTempFile(String,String,File)
     */
    public static File newTmpFileString content )
        throws IOException
    {
        return newTmpFilecontent, "ISO-8859-1" );
    }

    /**
     *  Runs a simple command in given directory.
     *  The environment is inherited from the parent process (e.g. the
     *  one in which this Java VM runs).
     *
     *  @return Standard output from the command.
     *  @param  command The command to run
     *  @param  directory The working directory to run the command in
     *  @throws IOException If the command failed
     *  @throws InterruptedException If the command was halted
     */
    public static String runSimpleCommandString command, String directory )
        throws IOException,
               InterruptedException
    {
        StringBuffer result = new StringBuffer();

        System.out.println("Running simple command "+command+" in "+directory);

        Process process = Runtime.getRuntime().execcommand, null, new File(directory) );

        BufferedReader stdout = null;
        BufferedReader stderr = null;

        try
        {
            stdout = new BufferedReadernew InputStreamReader(process.getInputStream()) );
            stderr = new BufferedReadernew InputStreamReader(process.getErrorStream()) );

            String line;

            while( (line = stdout.readLine()) != null )
            {
                result.appendline+"\n");
            }

            StringBuffer error = new StringBuffer();
            while( (line = stderr.readLine()) != null )
            {
                error.appendline+"\n");
            }

            iferror.length() )
            {
                System.out.println("Command failed, error stream is: "+error);
            }

            process.waitFor();

        }
        finally
        {
            // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
            process.getInputStream().close();
            ifstdout != null stdout.close();
            ifstderr != null stderr.close();
        }

        return result.toString();
    }


    /**
     *  Just copies all characters from <I>in</I> to <I>out</I>.  The copying
     *  is performed using a buffer of bytes.
     *
     *  @since 1.5.8
     *  @param in The reader to copy from
     *  @param out The reader to copy to
     *  @throws IOException If reading or writing failed.
     */
    public static void copyContentsReader in, Writer out )
        throws IOException
    {
        char[] buf = new char[BUFFER_SIZE];
        int bytesRead = 0;

        while ((bytesRead = in.read(buf)) 0)
        {
            out.write(buf, 0, bytesRead);
        }

        out.flush();
    }

    /**
     *  Just copies all bytes from <I>in</I> to <I>out</I>.  The copying is
     *  performed using a buffer of bytes.
     *
     *  @since 1.9.31
     *  @param in The inputstream to copy from
     *  @param out The outputstream to copy to
     *  @throws IOException In case reading or writing fails.
     */
    public static void copyContentsInputStream in, OutputStream out )
        throws IOException
    {
        byte[] buf = new byte[BUFFER_SIZE];
        int bytesRead = 0;

        while ((bytesRead = in.read(buf)) 0)
        {
            out.write(buf, 0, bytesRead);
        }

        out.flush();
    }

    /**
     *  Reads in file contents.
     *  <P>
     *  This method is smart and falls back to ISO-8859-1 if the input stream does not
     *  seem to be in the specified encoding.
     *
     *  @param input The InputStream to read from.
     *  @param encoding The encoding to assume at first.
     *  @return A String, interpreted in the "encoding", or, if it fails, in Latin1.
     *  @throws IOException If the stream cannot be read or the stream cannot be
     *          decoded (even) in Latin1
     */
    public static String readContentsInputStream input, String encoding )
        throws IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileUtil.copyContentsinput, out );

        ByteBuffer     bbuf        = ByteBuffer.wrapout.toByteArray() );

        Charset        cset        = Charset.forNameencoding );
        CharsetDecoder csetdecoder = cset.newDecoder();

        csetdecoder.onMalformedInputCodingErrorAction.REPORT );
        csetdecoder.onUnmappableCharacterCodingErrorAction.REPORT );

        try
        {
            CharBuffer cbuf = csetdecoder.decodebbuf );

            return cbuf.toString();
        }
        catchCharacterCodingException e )
        {
            Charset        latin1    = Charset.forName("ISO-8859-1");
            CharsetDecoder l1decoder = latin1.newDecoder();

            l1decoder.onMalformedInputCodingErrorAction.REPORT );
            l1decoder.onUnmappableCharacterCodingErrorAction.REPORT );

            try
            {
                bbuf = ByteBuffer.wrapout.toByteArray() );

                CharBuffer cbuf = l1decoder.decodebbuf );

                return cbuf.toString();
            }
            catchCharacterCodingException ex )
            {
                throw (CharacterCodingExceptionex.fillInStackTrace();
            }
        }
    }

    /**
     *  Returns the full contents of the Reader as a String.
     *
     *  @since 1.5.8
     *  @param in The reader from which the contents shall be read.
     *  @return String read from the Reader
     *  @throws IOException If reading fails.
     */
    public static String readContentsReader in )
        throws IOException
    {
        Writer out = null;

        try
        {
            out = new StringWriter();

            copyContentsin, out );

            return out.toString();
        }
        finally
        {
            try
            {
                out.close();
            }
            catchException e )
            {
                System.out.println("Not able to close the stream while reading contents.");
            }
        }
    }

    /**
     *  Returns the class and method name (+a line number) in which the
     *  Throwable was thrown.
     *
     *  @param t A Throwable to analyze.
     *  @return A human-readable string stating the class and method.  Do not rely
     *          the format to be anything fixed.
     */
    public static String getThrowingMethodThrowable t )
    {
        StackTraceElement[] trace = t.getStackTrace();
        StringBuffer sb = new StringBuffer();

        iftrace == null || trace.length == )
        {
            sb.append"[Stack trace not available]" );
        }
        else
        {
            sb.appendtrace[0].isNativeMethod() "native method" "" );
            sb.appendtrace[0].getClassName() );
            sb.append(".");
            sb.append(trace[0].getMethodName()+"(), line "+trace[0].getLineNumber());
        }
        return sb.toString();
    }
}

   
    
    
  
Related examples in the same category
1. Show the content of a file
2. Some general utility functions for dealing with Streams
3. Utility functions related to Streams
4. Utility methods for handling streams
5. Various utility methods that have something to do with I/O
6. General IO Stream manipulation
7. General IO stream manipulation utilities
8. Count the number of bytes read through the stream
9. Count OutputStream
10. File utilities for file read and write
11. An InputStream class that terminates the stream when it encounters a particular byte sequence.
12. An InputStream that implements HTTP/1.1 chunking
13. An OutputStream which relays all data written into it into a list of given OutputStreams
14. Utility code for dealing with different endian systems
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.