[英]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. 在Java中,是否有一种方法可以读取文件(文本文件),使其一次只读取一个字符,而不是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链接复制示例代码,但我发现这基本上与下面给出的答案相同。
ref: http://download.oracle.com/javase/tutorial/essential/io/charstreams.html 参考: 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 您可以使用InputStreamReader类中的read方法,该方法从流中读取一个字符,并在到达流末尾时返回-1
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: 通常,您可以使用
java.io
包中的任何Reader
来读取字符,例如:
// Read from file
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
// Read from sting
BufferedReader reader = new BufferedReader(new StringReader("Some text"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.