所以我刚刚开始学习Java FileI/O,并且一直在使用Input Stream Reader。然而,我做的一个练习的输出非常奇怪,也与我遵循的指南不符。
public static void main(String[] args)
throws InterruptedException
{
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
char s = 0;
while (s != 133) {
s = (char) cin.read();
System.out.println(s);
}
} catch (IOException e) {
System.out.println("File IO Error");
} finally {
try {
cin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}代码应该只打印字符,但它也会打印一堆换行符。
a
a
<linebreak>
<linebreak>
<linebreak>当我将char转换为int类型时,它输出字符id,然后输出13和10。
a
97
13
10有谁知道问题是什么+如何解决这个问题吗?
发布于 2017-07-13 05:03:07
read()将读取单个字符,当您按enter时,它也会读取回车符(换行符)并输出它的表示。
替换
System.out.println(s);使用
System.out.print(s);一般情况下,InputStreamReader是低级的,建议使用BufferedReader等包装器,如下所示(也可以解决你的问题)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tLine = null;
// now reading line of characters (delimited by carriage return)
while ((tLine = br.readLine()) != null) {
System.out.println(tLine);
} 另一个建议是使用try-with-resources,而不是传统的try-catch块。
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
// your code
}
// Resource will be closed automatically at this line发布于 2017-07-13 05:10:58
您的程序正在请求输入。要提供该输入,请按a,然后按<enter>。
该<enter>键成为输入流中的字符CR (十进制13)和LF (十进制10)。
结果是你的程序读取了3个字符。
发布于 2017-07-13 05:18:55
解决此问题的一种方法是添加:
if(System.getProperty("os.name").startsWith("Windows")){cin.skip(2);} // for Windows
else{cin.skip(1);} // for unix-like OS在System.out.println(s);行之后,在本例中,您的程序跳过了来自Enter的两个字符Line Feed和Carriage Return。

https://stackoverflow.com/questions/45067359
复制相似问题