如何在 Java 中逐个字符地读取输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/811851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read input character-by-character in Java?
提问by jergason
I am used to the c-style getchar()
, but it seems like there is nothing comparable for java. I am building a lexical analyzer, and I need to read in the input character by character.
我习惯了 c-style getchar()
,但似乎没有什么可与 java 相媲美的。我正在构建一个词法分析器,我需要逐个字符地读入输入。
I know I can use the scanner to scan in a token or line and parse through the token char-by-char, but that seems unwieldy for strings spanning multiple lines. Is there a way to just get the next character from the input buffer in Java, or should I just plug away with the Scanner class?
我知道我可以使用扫描仪扫描一个标记或行并逐个字符解析标记,但这对于跨越多行的字符串来说似乎很笨拙。有没有办法从 Java 的输入缓冲区中获取下一个字符,或者我应该直接插入 Scanner 类?
The input is a file, not the keyboard.
输入是一个文件,而不是键盘。
采纳答案by McDowell
Use Reader.read(). A return value of -1 means end of stream; else, cast to char.
使用Reader.read()。返回值 -1 表示流结束;否则,转换为char。
This code reads character data from a list of file arguments:
此代码从文件参数列表中读取字符数据:
public class CharacterHandler {
//Java 7 source level
public static void main(String[] args) throws IOException {
// replace this with a known encoding if possible
Charset encoding = Charset.defaultCharset();
for (String filename : args) {
File file = new File(filename);
handleFile(file, encoding);
}
}
private static void handleFile(File file, Charset encoding)
throws IOException {
try (InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
// buffer for efficiency
Reader buffer = new BufferedReader(reader)) {
handleCharacters(buffer);
}
}
private static void handleCharacters(Reader reader)
throws IOException {
int r;
while ((r = reader.read()) != -1) {
char ch = (char) r;
System.out.println("Do something with " + ch);
}
}
}
The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charsetclass for more. (If you feel masochistic, you can read this guide to character encoding.)
上面代码的坏处是它使用了系统的默认字符集。在可能的情况下,更喜欢已知的编码(理想情况下,如果您有选择,则使用 Unicode 编码)。有关更多信息,请参阅Charset类。(如果你觉得受虐狂,你可以阅读这个字符编码指南。)
(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Characterclass for more details; this is an edge case that probably won't apply to homework.)
(您可能需要注意的一件事是补充 Unicode 字符 - 那些需要存储两个 char 值的字符。有关更多详细信息,请参阅Character类;这是可能不适用于家庭作业的边缘情况。)
回答by shake
You have several options if you use BufferedReader
. This buffered reader is faster than Reader so you can wrap it.
如果您使用BufferedReader
. 这个缓冲阅读器比阅读器快,所以你可以包装它。
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
这将行读入字符数组。你有类似的选择。看文档。
回答by James
Wrap your reader in a BufferedReader, which maintains a buffer allowing for much faster reads overall. You can then use read() to read a single character (which you'll need to cast). You can also use readLine() to fetch an entire line and then break that into individual characters. The BufferedReader also supports marking and returning, so if you need to, you can read a line multiple times.
将您的阅读器包装在BufferedReader 中,它维护一个缓冲区,允许整体读取速度更快。然后您可以使用 read() 读取单个字符(您需要强制转换)。您还可以使用 readLine() 获取整行,然后将其分解为单个字符。BufferedReader 还支持标记和返回,因此如果需要,您可以多次读取一行。
Generally speaking, you want to use a BufferedReader or BufferedInputStream on top of whatever stream you are actually using since the buffer they maintain will make multiple reads much faster.
一般来说,您希望在实际使用的任何流之上使用 BufferedReader 或 BufferedInputStream,因为它们维护的缓冲区将使多次读取速度更快。
回答by pfranza
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
将输入流包装在缓冲读取器中,然后使用 read 方法一次读取一个字节,直到流结束。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
回答by roryparle
Combining the recommendations from others for specifying a character encoding and buffering the input, here's what I think is a pretty complete answer.
结合其他人关于指定字符编码和缓冲输入的建议,我认为这是一个非常完整的答案。
Assuming you have a File
object representing the file you want to read:
假设您有一个File
表示要读取的文件的对象:
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
// Do something with your character
}
回答by David
Another option is to not read things in character by character -- read the entire file into memory. This is useful if you need to look at the characters more than once. One trivial way to do that is:
另一种选择是不逐个字符地读取内容——将整个文件读入内存。如果您需要多次查看字符,这将非常有用。一种简单的方法是:
/** Read the contents of a file into a string buffer */
public static void readFile(File file, StringBuffer buf)
throws IOException
{
FileReader fr = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
char[] cbuf = new char[(int) file.length()];
br.read(cbuf);
buf.append(cbuf);
br.close();
}
finally {
if (fr != null) {
fr.close();
}
}
}
回答by samir vora
In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.
在 java 5 中添加了新功能,即 Scanner 方法,它提供了在 java 中逐个字符读取输入的机会。
for instance; for use Scanner method import java.util.Scanner; after in main method:define
例如; 用于使用 Scanner 方法导入 java.util.Scanner; 在主方法之后:定义
Scanner myScanner = new Scanner(System.in); //for read character
扫描仪 myScanner = new Scanner(System.in); //读取字符
char anything=myScanner.findInLine(".").charAt(0);
char 任何东西=myScanner.findInLine(".").charAt(0);
you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)
您可以存储单个字符,如果您想要更多阅读更多字符,请声明更多对象,例如任何事物1,任何事物2...更多答案示例请查看您的手(复制/粘贴)
import java.util.Scanner;
class ReverseWord {
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
char c1,c2,c3,c4;
c1 = myScanner.findInLine(".").charAt(0);
c2 = myScanner.findInLine(".").charAt(0);
c3 = myScanner.findInLine(".").charAt(0);
c4 = myScanner.findInLine(".").charAt(0);
System.out.print(c4);
System.out.print(c3);
System.out.print(c2);
System.out.print(c1);
System.out.println();
}
}
回答by W. B. Reed
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
如果我是你,我只会使用扫描仪并使用“.nextByte()”。你可以把它转换成一个字符,你很好。
回答by grant zukowski
This will print 1 character per line from the file.
这将从文件中每行打印 1 个字符。
try {
FileInputStream inputStream = new FileInputStream(theFile);
while (inputStream.available() > 0) {
inputData = inputStream.read();
System.out.println((char) inputData);
}
inputStream.close();
} catch (IOException ioe) {
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}