逐行比较两个文件的内容

时间:2013-08-26 06:02:31

标签: android file

public class MainActivity extends Activity {


    FileOutputStream fos;
    FileInputStream fOne, fTwo;
    ArrayList<String> arr1 = new ArrayList<String>();
    ArrayList<String> arr2 = new ArrayList<String>();

    ArrayList<String> words = new ArrayList<String>();
    ArrayList<String> wordsTwo = new ArrayList<String>();
    int count = 0;
    int countTwo = 0;
    int countThree = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button  fileOne = (Button)findViewById(R.id.file1);
        Button  fileTwo = (Button)findViewById(R.id.file2);
        Button  compare = (Button)findViewById(R.id.compare);
        arr1.add("1");
        arr1.add("2");
        arr1.add("3");
        arr1.add("4");
        //arr1.add("3");

        arr2.add("1");
        arr2.add("2");


        fileOne.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try
                {
                    fos = openFileOutput("File1", Context.MODE_PRIVATE);

                    for(int temp = 0; temp< arr1.size(); temp++)
                    {
                        fos.write((arr1.get(temp).getBytes()) );
                        fos.write(System.getProperty("line.separator").getBytes());

                    }
                    fos.close();
                    fos.flush();

                }

                catch(Exception e)
                {

                }
            }
        });


        fileTwo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try
                {
                    fos = openFileOutput("File2", Context.MODE_PRIVATE);

                    for(int temp = 0; temp< arr2.size(); temp++)
                    {
                        fos.write((arr2.get(temp).getBytes()) );
                        fos.write(System.getProperty("line.separator").getBytes());

                    }
                    fos.close();
                    fos.flush();

                }

                catch(Exception e)
                {

                }
            }
        });

        compare.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try
                {
                    fOne = openFileInput("File1");
                    fTwo = openFileInput("File2");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Scanner scanFile = new Scanner(new DataInputStream(fOne));
                Scanner scanFileT = new Scanner(new DataInputStream(fTwo));
                words = new ArrayList<String>();
                wordsTwo = new ArrayList<String>();

                while (scanFile.hasNextLine())
                {
                    if(scanFile.nextLine()!=null)
                    {
                        count++;
                    }

                    while(scanFileT.hasNextLine())
                    {
                        if(scanFileT.nextLine()!=null)
                        {
                            countTwo++;

                        }
                    }
                }

                try 
                {
                    fOne.close();
                    fTwo.close();
                    scanFile.close();
                    scanFileT.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                Toast.makeText(getBaseContext(), "One : " + count, 1000).show();
                Toast.makeText(getBaseContext(), "Two : " + countTwo, 1000).show();
                Toast.makeText(getBaseContext(), "Three : " + countThree, 1000).show();
                count = 0 ;                         
                countTwo = 0;
                countThree = 0;
            }
        });
    }



}

以上是编写和读取文件的代码。我在这里做了什么,写了两个文件并阅读了内容..现在我必须逐行比较文件的内容。需要做什么?

3 个答案:

答案 0 :(得分:2)

尝试以下代码。这将为您提供所需的输出。我从资产目录中获取了文件。因此,如果要从其他目录中获取文件,则需要替换该行代码。

private void compareFiles() throws Exception {

    String s1 = "";
    String s2 = "", s3 = "", s4 = "";
    String y = "", z = "";

    // Reading the contents of the files
    BufferedReader br = new BufferedReader(new InputStreamReader(
            getAssets().open("first.txt")));
    BufferedReader br1 = new BufferedReader(new InputStreamReader(
            getAssets().open("second.txt")));

    while ((z = br1.readLine()) != null) {
        s3 += z;
        s3 += System.getProperty("line.separator");
    }

    while ((y = br.readLine()) != null) {
        s1 += y;
        s1 += System.getProperty("line.separator");
    }

    // String tokenizing
    StringTokenizer st = new StringTokenizer(s1);
    String[] a = new String[10000];
    for (int l = 0; l < 10000; l++) {
        a[l] = "";
    }
    int i = 0;
    while (st.hasMoreTokens()) {
        s2 = st.nextToken();
        a[i] = s2;
        i++;
    }

    StringTokenizer st1 = new StringTokenizer(s3);
    String[] b = new String[10000];
    for (int k = 0; k < 10000; k++) {
        b[k] = "";
    }
    int j = 0;
    while (st1.hasMoreTokens()) {
        s4 = st1.nextToken();
        b[j] = s4;
        j++;
    }

    // comparing the contents of the files and printing the differences, if
    // any.
    int x = 0;
    for (int m = 0; m < a.length; m++) {
        if (a[m].equals(b[m])) {
        } else {
            x++;
            Log.d("Home", a[m] + " -- " + b[m]);
        }
    }
    Log.d("Home", "No. of differences : " + x);
    if (x > 0) {
        Log.d("Home", "Files are not equal");
    } else {
        Log.d("Home", "Files are equal. No difference found");
    }
}

输入文件1

  1. 您好
  2. 你好
  3. Chintan
  4. Rathod
  5. 输入文件2

    1. 您好
    2. HELLO
    3. Chintan
    4. RathoD
    5. <强>输出

      08-26 12:07:58.219:DEBUG / Home(2350):Hello3。 - HellO3。
      08-26 12:07:58.219:DEBUG / Home(2350):Rathod - RathoD
      08-26 12:07:58.229:DEBUG / Home(2350):差异数量:2
      08-26 12:07:58.229:DEBUG / Home(2350):文件不相等

      修改

      获取两个文件之间的差异

      使用Apache提供的 StringUtils 库,并查看 Documentation ,了解有关该库的更多信息。

      修改以下代码行。

      int x = 0;
      for (int m = 0; m < a.length; m++) {
          if (a[m].equals(b[m])) {
          } else {
              x++;
              Log.d("Home", a[m] + " -- " + b[m]);
              //to print difference   
              if (a[m].length() < b[m].length())
                  Log.d("Home", "" + StringUtils.difference(a[m], b[m]));
              else
                  Log.d("Home", "" + StringUtils.difference(b[m], a[m]));
          }       
      }
      

      <强>输出

      08-26 17:51:26.949:DEBUG / Home(17900):12 - 123
      08-26 17:51:26.949:DEBUG / Home(17900):差异字符串:3
      08-26 17:51:26.949:DEBUG / Home(17900):差异数量:1
      08-26 17:51:26.949:DEBUG / Home(17900):文件不相等

答案 1 :(得分:1)

尝试使用java.util.Scanner

  while (sc1.hasNext() && sc2.hasNext()) {
        String str1 = sc1.next();
        String str2 = sc2.next();
        if (!str1.equals(str2))
            System.out.println(str1 + " != " + str2);
    }

答案 2 :(得分:0)

将while循环更改为以下内容:

while (scanFile.hasNextLine() && scanFileT.hasNextLine())
{
    if(scanFileT.nextLine().equals(scanFile.nextLine()))
    {
        // The lines are equal.
    } else {
        // The lines are not equal.
    }
}

if(scanFile.hasNextLine() || scanFileT.hasNextLine())
{
    // If more lines remain in one of the files, they are not equal.
} else {
    // If no content remains in both files, they are equal.
}

根据文件的大小,我建议进行一些优化,例如在逐行检查之前检查文件大小。

整体逻辑如下:如果两个都有另一条线,比较它是否相等。如果他们没有其他行,请检查其中一行是否有剩余行,如果有,则不相等。

<强>更新 在澄清了聊天中的比较目标之后,看到对这个问题的评论,我得出的结论是,另一种比较会更有效,而且事实上是正确的。如果比较文本结构,则上述比较算法效果很好,但如果比较可能排序或不排序的数据矢量则不然。经过一些讨论后,我们得出的结论是,数据需要进行排序,或者比较会将复杂性降至至少O(n^2),如果数据已排序,可以在O(2n)中完成。这里是算法的骨架:

if(! scanGroupFriends.hasNextLine())
{
    //simple sanity check to see if we need to compare at all. In this case, add all friends.
} else {
    String nextFriend = scanGroupFriends.nextLine();

    while(scanAllFriends.hasNextLine())
    {
        if(scanAllFriends.nextLine().equals(nextFriend))
        {
            // Friend already figures, do not add him and advance the list of group friends.
            if(scanGroupFriends.hasNextLine())
            {
                nextFriend = scanGroupFriends.nextLine();
            } else {
                // There are no more friends in the group, add all remaining friends to list to show.
                break; // Terminate the `while` loop.
            }
        }
    }
}

然而,我个人认为做出许多假设是不好的。我建议将朋友保存在SetTreeSet中。然后,序列化对象而不是手动将其写入文件。集合很整洁,因为它们包含几个有趣的对象。例如,您可以轻松地使用以下代码从所有朋友的集合中删除组中的所有朋友:

allFriends.removeAll(groupFriends);

但是,请注意,这会将其从集合中完全删除,因此您应事先制作副本。