Java 7:包含其他文件路径的文件

时间:2015-08-05 15:58:30

标签: java file path java-7

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

  1. 在阅读模式下打开一个文件,其中包含每行的另一个文件的路径
  2. 对于每个行/路径,打开相应的文件并打印内容
  3. (每个文件都是纯文本文件)

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

    谢谢

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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();
}