使用方法组合文本文件

时间:2014-11-14 05:58:14

标签: java methods io

大家好,我目前正在尝试编写一个程序,用于分配4个单独的文本文件,然后使用方法,将它们合并为一个。我想知道是否有人可以帮我找出这段代码有什么问题。当我尝试运行它时,我得到一个错误,阅读以下内容:

"Exception in thread "main" java.io.FileNotFoundException: wonder1.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at asig5.combineFile(asig5.java:26)
    at asig5.main(asig5.java:17) "

代码:

import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class asig5 {

    public static void main(String[] args) throws FileNotFoundException {

        PrintWriter newtext = new PrintWriter("wonder5.txt");
        File f0 = new File("wonder1.txt");
        File f1 = new File("wonder2.txt");
        File f2 = new File("wonder3.txt");
        File f3 = new File("wonder4.txt");
        combineFile(f0, newtext);
        combineFile(f1, newtext);
        combineFile(f2, newtext);
        combineFile(f3, newtext);

        newtext.close();

    }

    public static void combineFile(File f0, PrintWriter output) throws FileNotFoundException {
        Scanner input = new Scanner(f0);
        while (input.hasNext()) {

            String part1 = input.nextLine();
            System.out.println(part1);
            output.print(part1);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

当您撰写new File("wonder1.txt")时,表示如果您的项目位置为~/Folder/MyProject,则您文件的完整路径为~/Folder/MyProject/wonder1.txt

您需要提供文件的完整路径或将文件放在项目文件夹的根目录中。