Reading in from text file character by character

40,456

Solution 1

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
             }
        }
    }

Solution 2

You can read the whole file (if it is not much big) in the memory as string, and iterate on the string character by character

Solution 3

There are several possible solutions. Generally you can use any Reader from java.io package for reading characters, e.g.:

// Read from file
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
// Read from sting
BufferedReader reader = new BufferedReader(new StringReader("Some text"));
Share:
40,456
Chris Marker
Author by

Chris Marker

Updated on July 09, 2022

Comments

  • Chris Marker
    Chris Marker almost 2 years

    In Java, is there a way of reading a file (text file) in a way that it would only read one character at a time, rather than String by String. This is for the purpose of an extremely basic lexical analyzer, so you can understand why I'd want such a method. Thank you.

  • Ahmed
    Ahmed over 12 years
    It is an answer, do you think it should contain a code to be an answer!