gpt4 book ai didi

java - 从文件读取输入流打印丢失的字符

转载 作者:行者123 更新时间:2023-12-01 20:57:19 25 4
gpt4 key购买 nike

我正在 java 中使用 BufferedReader 从输入文件中读取字符。然而,输出却异常。在下面的代码中,我首先使用扫描仪显示文件本身的内容,然后使用 BufferedReader 打印每个单独的字符:

import java.util.Scanner;
import java.io.*;
//import java.io.File;

public class Inputs
{


public static void main(String[] args)
{
System.out.println("Inputs");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println(input);
// Open the file
File file = new File("Simple.java");
try {

Scanner fileIn = new Scanner(file);

while(fileIn.hasNext()){
System.out.println(fileIn.next());

}
fileIn.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}

try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}






}
}

下面是我得到的输出,显示的第一个标记是由扫描仪显示的,但在突出显示的学徒之后是 BufferedReaders 的输出。它打印 3 个空格,然后打印一个闭花括号,然后打印 -1(结束)。这是什么意思?

enter image description here

最佳答案

在您的代码中,您正在使用 br.readline() 在 while 循环条件下读取该行。然后在循环体中,您再次使用 br.read() 读取字符。因此打印每行的第一个字符。

while ((strLine = br.readLine()) != null)   {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}

要解决此问题,可以使用 Halko Sajtarevic 提到的方法(但每个字符都被读取为整数并转换回字符串),或者只需消除第二次读取字符并仅打印字符串。

while ((strLine = br.readLine()) != null)   {
// Print the content on the console
System.out.println (strLine);
}

关于java - 从文件读取输入流打印丢失的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42108735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com