File utilities for file read and write : 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 
File utilities for file read and write
   
/*
  Milyn - Copyright (C) 2006

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License (version 2.1) as published by the Free Software
  Foundation.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  See the GNU Lesser General Public License for more details:
  http://www.gnu.org/licenses/lgpl.txt
*/

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;

/**
 * File utilities.
 @author <a href="mailto:tom.fennelly@jboss.com">tom.fennelly@jboss.com</a>
 */
public abstract class FileUtils {
    
    public static void copyFile(String from, String tothrows IOException {
        File fromFile = new File(from);
        File toFile = new File(to);

        writeFile(readFile(fromFile), toFile);
    }

    /**
     * Read the contents of the specified file.
     @param file The file to read.
     @return The file contents.
     @throws IOException Error readiong file.
     */
    public static byte[] readFile(File filethrows IOException {


        if(!file.exists()) {
            throw new IllegalArgumentException("No such file '" + file.getAbsoluteFile() "'.");
        else if(file.isDirectory()) {
            throw new IllegalArgumentException("File '" + file.getAbsoluteFile() "' is a directory.  Cannot read.");
        }

        InputStream stream = new FileInputStream(file);
        try {
            return StreamUtils.readStream(stream);
        finally {
            stream.close();
        }
    }

    public static void writeFile(byte[] bytes, File filethrows IOException {
        if(file.isDirectory()) {
            throw new IllegalArgumentException("File '" + file.getAbsoluteFile() "' is an existing directory.  Cannot write.");
        }

        FileOutputStream stream = new FileOutputStream(file);
        try {
            stream.write(bytes);
            stream.flush();
        finally {
            stream.close();
        }
    }
}
/*
Milyn - Copyright (C) 2006

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software 
Foundation.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  

See the GNU Lesser General Public License for more details:    
http://www.gnu.org/licenses/lgpl.txt
*/



/**
* Stream Utilities.

@author tfennelly
*/
abstract class StreamUtils {

  /**
   * Read the supplied InputStream and return as a byte array.
   
   @param stream
   *            The stream to read.
   @return byte array containing the Stream data.
   @throws IOException
   *             Exception reading from the stream.
   */
  public static byte[] readStream(InputStream streamthrows IOException {


       ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    byte[] byteBuf = new byte[1024];
    int readCount = 0;

    while ((readCount = stream.read(byteBuf)) != -1) {
      bytesOut.write(byteBuf, 0, readCount);
    }

    return bytesOut.toByteArray();
  }

   /**
    * Read the supplied InputStream and return as a byte array.
    *
    @param stream
    *            The stream to read.
    @return A String containing the Stream data.
    @throws IOException
    *             Exception reading from the stream.
    */
   public static String readStreamAsString(InputStream streamthrows IOException {


       return new String(readStream(stream));
   }

   public static byte[] readFile(File filethrows IOException {

       InputStream stream = new FileInputStream(file);
       try {
           return readStream(stream);
       finally {
           stream.close();
       }
   }

   public static void writeFile(File file, byte[] datathrows IOException {

       OutputStream stream = new FileOutputStream(file);
       try {
           stream.write(data);
       finally {
           try {
               stream.flush();
           finally {
               stream.close();
           }
       }
   }

   public static String readStream(Reader streamthrows IOException {

       StringBuffer streamString = new StringBuffer();
       char[] readBuffer = new char[256];
       int readCount = 0;

       while ((readCount = stream.read(readBuffer)) != -1) {
           streamString.append(readBuffer, 0, readCount);
       }

       return streamString.toString();
   }

   /**
    * Compares the 2 streams.
    * <p/>
    * Calls {@link #trimLines(InputStream)} on each stream before comparing.
    @param s1 Stream 1.
    @param s2 Stream 2.
    @return True if the streams are equal not including leading and trailing
    * whitespace on each line and blank lines, otherwise returns false.
    */
   public static boolean compareCharStreams(InputStream s1, InputStream s2) {
       StringBuffer s1Buf, s2Buf;

       try {
           s1Buf = trimLines(s1);
           s2Buf = trimLines(s2);

           return s1Buf.toString().equals(s2Buf.toString());
       catch (IOException e) {
           // fail the comparison
       }

       return false;
   }

   /**
    * Compares the 2 streams.
    * <p/>
    * Calls {@link #trimLines(java.io.Reader)} on each stream before comparing.
    @param s1 Stream 1.
    @param s2 Stream 2.
    @return True if the streams are equal not including leading and trailing
    * whitespace on each line and blank lines, otherwise returns false.
    */
   public static boolean compareCharStreams(Reader s1, Reader s2) {
       StringBuffer s1Buf, s2Buf;

       try {
           s1Buf = trimLines(s1);
           s2Buf = trimLines(s2);

           return s1Buf.toString().equals(s2Buf.toString());
       catch (IOException e) {
           // fail the comparison
       }

       return false;
   }


   /**
    * Compares the 2 streams.
    * <p/>
    * Calls {@link #trimLines(java.io.Reader)} on each stream before comparing.
    @param s1 Stream 1.
    @param s2 Stream 2.
    @return True if the streams are equal not including leading and trailing
    * whitespace on each line and blank lines, otherwise returns false.
    */
   public static boolean compareCharStreams(String s1, String s2) {
       return compareCharStreams(new StringReader(s1)new StringReader(s2));
   }

   /**
    * Read the lines lines of characters from the stream and trim each line
    * i.e. remove all leading and trailing whitespace.
    @param charStream Character stream.
    @return StringBuffer containing the line trimmed stream.
    @throws IOException
    */
   public static StringBuffer trimLines(Reader charStreamthrows IOException {
       StringBuffer stringBuf = new StringBuffer();
       BufferedReader reader = new BufferedReader(charStream);
       String line;

       while((line = reader.readLine()) != null) {
           stringBuf.append(line.trim());
       }

       return stringBuf;
   }

   /**
    * Read the lines lines of characters from the stream and trim each line
    * i.e. remove all leading and trailing whitespace.
    @param charStream Character stream.
    @return StringBuffer containing the line trimmed stream.
    @throws IOException
    */
   public static StringBuffer trimLines(InputStream charStreamthrows IOException {
       return trimLines(new InputStreamReader(charStream, "UTF-8"));
   }
}

   
    
    
  
Related examples in the same category
1. Show the content of a file
2. Some general utility functions for dealing with Streams
3. Utilities related to file and stream handling.
4. Utility functions related to Streams
5. Utility methods for handling streams
6. Various utility methods that have something to do with I/O
7. General IO Stream manipulation
8. General IO stream manipulation utilities
9. Count the number of bytes read through the stream
10. Count OutputStream
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.