我不明白为什么下面的代码似乎跳过了第一个输入字符。
import java.io.*;
import java.util.Arrays;
public class Input
{
public static void main (String args[])
{
try {
echo(System.in);
}
catch (IOException e) {
e.printStackTrace();
}
}
static void echo(InputStream stream) throws IOException
{
byte[] input = new byte[10];
char[] inputChar = new char[10];
int current;
while ((current = stream.read()) > 0){
stream.read(input);
int i = 0;
while (input[i] != 0) {
inputChar[i] = (char)input[i];
if (i < 9) {
i++;
}
else {
break;
}
}
System.out.println(Arrays.toString(inputChar));
}
}
}
如果我输入“1234567890”,我得到的输出是“[2, 3, 4, 5, 6, 7, 8, 9, 0,]” inputChar 中的最后一个字符似乎是空白。但是,如果它没有将任何字节读入 input[9],它应该是空字符 (ASCII 0)。如果我给出的输入长度小于 10 个字符,我将在 inputChar 中的剩余位置得到空字符。所以我不确定这里发生了什么。
最佳答案
同时 ((current = stream.read()) > 0){
这里是您的第一次阅读,您没有使用它,但这是一次实际阅读,将提高您在信息流中的“位置”。
关于java - 从输入流读取时缺少第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487391/