john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

file read scanner write buffered streams

BufferedInputStream and BufferedOutputStream create buffered byte streams.
BufferedReader and BufferedWriter create buffered character streams.

inputStream = new BufferedReader( new FileReader( "filereadbychars.txt") );
outputStream = new BufferedWriter( new FileWriter( "filewritebychars.txt") );

An autoflush PrintWriter object flushes the buffer on every invocation of println or format.
To flush a stream manually invoke its flush method.

// Unbuffered example
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class WriteFileExample
{
    private static String filename = "temp.txt";

    public static void main( String args[] )
    {
        try {
            FileWriter outFile = new FileWriter( filename );
            PrintWriter out = new PrintWriter( outFile );
            out.println( "First line of text" );
            out.close();

      } catch (IOException e)
      {
        e.printStackTrace();
      }
    }
}//end class

// read in and "scan" until whitespace, then print out that word
import java.io.*;
import java.util.Scanner;

public class myScan
{
  public static void main(String[] args) throws IOException
  {
    Scanner s = null;
    try {
      s = new Scanner( new BufferedReader( new FileReader( "inputfile.txt" ) ));

      while( s.hasNext() )
      {
        System.out.println( s.next() );
      }
    }finally {
        if (s != null) {    s.close();  }
    }

  } //end main
}// end class

  • « Network bridge brctl
  • command line process runtime exec system os properties »

Published

Jul 18, 2011

Category

java

~144 words

Tags

  • buffered 1
  • file 92
  • java 252
  • read 14
  • scanner 3
  • streams 1
  • write 10