【发布时间】:2017-02-08 09:03:57
【问题描述】:
我在 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(结束)。这是什么意思?
【问题讨论】:
-
这个问题看起来很酷。
-
您的代码没有意义。您正在读取行,然后打印 next 字符,无论它是什么,即使它是 -1 表示流结束。如果要打印文件,请打印您阅读的行。
标签: java java.util.scanner bufferedreader