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



}

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

4

3 回答 3

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. 钦坦
  4. 拉索

输入文件 2

  1. 你好
  2. 你好
  3. 钦坦
  4. 拉托德

输出

08-26 12:07:58.219:调试/主页(2350):Hello3。- 地狱O3。
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 :调试/主页(2350):文件不相等

编辑

获取两个文件之间的差异

使用Apache 提供的StringUtils库并查看此文档以了解有关该库的更多信息。

并修改以下代码行。

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):文件不相等

于 2013-08-26T06:38:30.370 回答
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);
    }
于 2013-08-26T06:05:29.433 回答
0

Change your while loop to the following:

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.
}

Depending on the size of your file, I would recommend some optimisation like checking the file sizes before you go through them line by line.

The overall logic reads as follows; if both have another line, compare it to see if it is equal. If they don't have another line, check if one of them has lines remaining, if so, they are not equal.

Update After clarifying the objective of the comparison in chat, see the comments to this question, I have come to the conclusion that another comparison would be more effective and, as a matter of fact, correct. The comparison algorithm above works great if comparing the structure of text but not if comparing a data vector which may or may not be sorted. After some discussion, we came to the conclusion that data needs to be sorted or the comparison will blow the complexity to at least O(n^2)which could be done in O(2n) if the data is sorted. Here the algorithm's skeleton:

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.
            }
        }
    }
}

However, I personally think it is bad to make to many assumptions. What I would suggest is that the friends be saved in a Set, a TreeSet for example. Then, serialize the object rather than manually writing it to file. Sets are neat because they hold several interesting objects. For example, you could easily use the following code to remove all friends in a group from the set of all friends:

allFriends.removeAll(groupFriends);

However, be aware that this removes it from the set completely so you should make a copy beforehand.

于 2013-08-26T06:13:58.687 回答