0

我对 java I/O 类很陌生,发现很难检测到代码中的错误。我想输入两个包含不同数字列表的文本文件的路径,以便程序将逐行比较这两个列表并生成一个单独的文本文件,其中包含输入文本文件中的公共数字。输入文件被带入程序,但它不会从那里继续。

提前致谢。

公共类 ListMatching {

public static String path1,path2; //paths of the input text files
public static String line1,line2 = null; //indivdual lines extracted from the files

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

    Scanner path = new Scanner(System.in);
    path1 = path.nextLine();
    path2 = path.nextLine();

    fileRead();
}


public static void fileRead () throws IOException {

    FileReader file1 = new FileReader(new File(path1));
    FileReader file2 = new FileReader(new File(path2));

    BufferedReader br1 = new BufferedReader(file1);
    BufferedReader br2 = new BufferedReader(file2);

    while ((line1 = br1.readLine())!=null){
       while((line2 = br2.readLine())!=null){

                    }
                    }
} }





 public static void writeFile() throws IOException{
    Scanner path = new Scanner(System.in);
    String outPath = path.nextLine();
    FileWriter fr = new FileWriter(new File(outPath));
    BufferedWriter br = new BufferedWriter (fr);

    br.append(line2);



 }

}

4

1 回答 1

0

你需要这样的东西:

    public class MyClass {
    private String path1;
    private String path2;
    private String resultFilePath;

    public void doCompare() throws Exception {
        BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream(path1)));
        BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(path2)));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultFilePath)));

        String line1 = null;
        String line2 = null;

        while ((line1 = reader1.readLine()) != null && (line2 = reader2.readLine()) != null)
            if (line1.trim().equals(line2.trim()))
                writer.append(line1).append("\r\n");
        writer.flush();
        writer.close();
        reader1.close();
        reader2.close();
    }
}
于 2013-11-11T07:48:27.550 回答