【问题标题】:Java 7: a file containing paths to other files [closed]Java 7:包含其他文件路径的文件[关闭]
【发布时间】:2015-10-28 12:24:31
【问题描述】:

是否有任何简单的方法(在 Java 7 中):

  1. 以阅读模式打开一个文件,其中每行包含另一个文件的路径
  2. 对于每一行/路径,打开相应的文件并打印内容

(每个文件都是纯文本文件)

?

对不起,如果这个问题很愚蠢。

谢谢

【问题讨论】:

  • 是的。打开文件,然后使用循环和扫描仪读取每一行。对于每一行,(尝试)使用该路径打开一个新文件,循环并打印每一行..然后继续下一个文件。太容易了:)
  • 这个问题有很多解决方案。到目前为止,您尝试了哪些方法,但在哪些方面没有奏效?
  • 这是一个直截了当的问题,你应该可以自己解决
  • Files.readAllLines 可能是阅读所有行的开始。

标签: java file path java-7


【解决方案1】:

试试这样的:

public static void main(String[] args) throws IOException {
    // open stream to path list file
    InputStream indexSource = new FileInputStream("index.txt");

    // create reader to read content
    try(BufferedReader stream = new BufferedReader(new InputStreamReader(indexSource))) {
        // loop
        while (true) {
            // read line
            String line = stream.readLine();
            if (line == null) {
                // stream reached end, escape the loop
                break;
            }
            // use `line`
            printFile(line);
        }
    }
}

static void printFile(String path) throws IOException {
    // open stream to text file
    InputStream textSource = new FileInputStream(path);

    // print file path
    System.out.println("### " + path + " ###");
    // create reader to read content
    try(BufferedReader stream = new BufferedReader(new InputStreamReader(textSource))) {
        // loop
        while (true) {
            // read line
            String line = stream.readLine();
            if (line == null) {
                // stream reached end, escape the loop
                break;
            }
            // print current line
            System.out.println(line);
        }
    }
    // nicer formatting
    System.out.println();
}

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 2015-11-08
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2014-10-21
    相关资源
    最近更新 更多