简体   繁体   English

比较两个导入的文本文件

[英]Compare two imported text file

Hey guys just wanted to see if what I'm thinking will work, I am in my second semester of learning java. 嘿,大家只是想看看我在想什么能奏效,我正在学习Java的第二学期。 Here's the directions for a hw assignment: Design a class that checks if the contents of two text files are identical and, if not, determines how many lines are different. 这是硬件分配的说明:设计一个类,该类检查两个文本文件的内容是否相同,如果不相同,则确定多少行不同。 Lines are different if they differ in one or more characters. 如果行的一个或多个字符不同,则行也不同。 So, I'm thinking that I should read in the texts line by line, convert each line to a string and then store each line in a spot in an array.Once I have done this I will have to arrays. 因此,我认为我应该逐行阅读文本,将每一行转换为字符串,然后将每一行存储在数组中的某个位置。一旦完成此操作,我就必须要数组。 Then, I plan on going through each array and comparing them. 然后,我计划遍历每个数组并进行比较。 Is my thinking on this problem correct? 我对这个问题的想法正确吗?

import java.io.*;
import java.util.*;

public class myfilereader
{
    public static void main (String[] args) throws java.io.IOException
    {
        ArrayList<String> Diff = new ArrayList<String>();
        Scanner s = new Scanner(new File("/Users/Home/Desktop/File2.txt"));
        ArrayList<String> ArrayList1 = new ArrayList<String>();
        while (s.hasNext())
        {
            ArrayList1.add(s.next());
        }
        s.close();

        Scanner s1 = new Scanner(new File("/Users/Home/Desktop/File1.txt"));
        ArrayList<String> ArrayList2 = new ArrayList<String>();
        while (s.hasNext())
        {
            ArrayList2.add(s1.next());
        }
        s1.close();
        HashSet hs = new HashSet();
        for(String i : ArrayList1) hs.add(i);
        for(String i : ArrayList2)
        {
            if(!hs.add(i))
                Diff.add(i);
        }

        String result = "+";
        for (int i = 0; i < Diff.size(); i++)
        {   
            result += " " + Diff.get(i);
        }
        System.out.println(result);

    }
}

Here are the exact errors I'm getting" 这是我得到的确切错误”

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Scanner.java:1046)
    at java.util.Scanner.hasNext(Scanner.java:1310)
    at myfilereader.main(myfilereader.java:19)

我将使用它: Apache Commons Collections然后将两个文件加载到ArrayList中,并使用Collections方法之一

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

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