简体   繁体   中英

Reading in from text file character by character

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.

Here's a sample code for reading / writing 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 was updated to copy the sample code from the Ref link, but I see this is essentially the same answer given below.

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

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

你可以在内存中读取整个文件(如果它不是很大)作为字符串,并逐个字符地迭代字符串

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM