Reading from a text file by character

In Java, there is a way to read a file (text file) in such a way that it will only read one character at a time, not String by String. This is done in order to use a basic lexical analyzer, so you can understand why I would like to get such a method. Thank.

+5
source share
4 answers

Here is an example code to read / write one character at a time

public class CopyCharacters {
    public static void main(String[] args) throws IOException {

        FileReader inputStream = null;
        FileWriter outputStream = null;

        try {
            inputStream = new FileReader("xanadu.txt");
            outputStream = new FileWriter("characteroutput.txt");

            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

Note. This answer has been updated to copy the sample code from the Ref link, but I can see that this is essentially the same answer as given below.

ref: http://download.oracle.com/javase/tutorial/essential/io/charstreams.html

+5
source

( )

+3

You can use the read method from the InputStreamReader class, which reads one character from the stream and returns -1 when it reaches the end of the stream.

   public static void processFile(File file) throws IOException {
        try (InputStream in = new FileInputStream(file);
             Reader reader = new InputStreamReader(in)) {

             int c;
             while ((c = reader.read()) != -1) {
                processChar((char) c);  // this method will do whatever you want
             }
        }
    }
+1
source

There are several possible solutions. Typically, you can use any package Readerfrom java.ioto read characters, for example:

// Read from file
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
// Read from sting
BufferedReader reader = new BufferedReader(new StringReader("Some text"));
0
source

All Articles