从多个.txt文件中读取和显示数据

时间:2016-01-07 23:53:06

标签: java

如何从多个.txt文件中读取数据?我希望能够在程序中打印两个.txt文件的内容,但我只知道如何做一个。

2 个答案:

答案 0 :(得分:0)

使用两个变量(我没有测试过代码,但这是基本的想法):

// Open both files
FileInputStream fis1 = new FileInputStream("file1.txt");
BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1));

FileInputStream fis2 = new FileInputStream("file2.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));

String strLine1;
String strLine2;

// Read and print a line from each file
while ((strLine1 = br1.readLine()) != null || (strLine2 = br2.readLine()) != null) {
  System.out.println (strLine1);
  System.out.println (strLine2);
}

// Close the FileInputStreams
br1.close();
br2.close();

答案 1 :(得分:-1)

您可以创建两个流并分别从它们中读取文件。

ObjectInputStream in1 = new ObjectInputStream(new FileInputStream("file1.dat");
ObjectInputStream in2 = new ObjectInputStream(new FileInputStream("file2.dat");

Object obj1 = in1.readObject();
Object obj2 = in2.readObject();

我认为这应该有效(将Object更改为对象的类型并转换readObject函数的返回值)。

但是既然你想输入两个文本文件,最好使用Scanner类:

    Scanner in1 = new Scanner(new File("file1.txt"));
    Scanner in2 = new Scanner(new File("file2.txt"));
    String s = null;
    while (s += in1.nextLine() != null);
    while (s += in2.nextLine() != null);
    System.out.println(s);

实际上你应该添加一个try catch块,但基本上就是这样。