Read from a text file char by char in Java

Description

The following code shows how to read from a text file char by char.

Example


/*from   ww w. j  a  va 2s . c  om*/
import java.io.FileInputStream;

public class Main {

  public static void main(String[] args) throws java.io.IOException {
    FileInputStream in = new FileInputStream("a.bat");
    StringBuffer buf = new StringBuffer();
    int c;
    do {
      c = in.read();
      buf.append( c);
    } while (c != -1);
    in.close();
    System.out.println(buf);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip