简体   繁体   English

如何读取多个.txt 文件以使用 Scanner 进行编程?

[英]How do I read multiple .txt files in to program with Scanner?

I have a program where I read in a.txt file using a scanner, and the code that follows prints out the sum of the integers in the.txt file.我有一个程序,我使用扫描仪读取 .txt 文件,随后的代码打印出 .txt 文件中整数的总和。

To read in another.txt file to get the sum for that file, I have to manually change the code to point to the new file.要读取 another.txt 文件以获取该文件的总和,我必须手动更改代码以指向新文件。 I would like to know how I can setup the program so that it will automatically iterate to the next file and print the sum.我想知道如何设置程序,以便它自动迭代到下一个文件并打印总和。

I'm using just basic scanner logic to read in the file.我只使用基本的扫描仪逻辑来读取文件。

Scanner txt = new Scanner(new File("/Users/.../25000.txt"));
        String line = txt.nextLine();
        String[] ne = line.split(" ");

I only have two files that I want to do this for: 1000.txt 25000.txt我只有两个要执行此操作的文件: 1000.txt 25000.txt

You can create an array of file names and then iterate the array eg您可以创建一个文件名数组,然后迭代该数组,例如

String[] files = { "/Users/.../25000.txt", "/Users/.../35000.txt", "/Users/.../45000.txt" };
for (String file : files) {
    Scanner txt = new Scanner(new File(file));
    String line = txt.nextLine();
    String[] ne = line.split(" ");
    // ...
    txt.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM