文本文件的字符串比较

时间:2012-06-06 07:22:41

标签: java android

  

可能重复:
  Compare the content of 2 text files in java language

我正在尝试比较Android应用程序中两个.txt文件的字符串。你能告诉我怎么办吗? 我想在此

中插入代码
try {
     URL url = new URL("httpurl");                             
     URLConnection ucon = url.openConnection();
     InputStream is = ucon.getInputStream();
     BufferedInputStream bis = new BufferedInputStream(is);
     ByteArrayBuffer baf = new ByteArrayBuffer(50);
     int current = 0;
     while ((current = bis.read()) != -1) {
           baf.append((byte) current);
     }

     FileOutputStream fos = new FileOutputStream("/mnt/sdcard/random.txt");
     fos.write(baf.toByteArray());
     fos.close();
} catch (IOException e) {
     Log.d("ImageManager", "Error: " + e);
}

2 个答案:

答案 0 :(得分:4)

你不应该将整个文件读入内存然后进行比较!

您可以以块状方式读取这两个文件,比较每个块对,如果块不同则停止读取。您还应该为块重用内存缓冲区。

这种方法可以让您早日停止(对性能有益)并管理内存(因此您可以比较非常大的文件)

请记住,这是一项耗时的操作,因此您不应该在UI线程中执行此操作。请使用AsyncTask

另外,我建议在读取文件之前比较文件大小。这是非常快的,如果文件具有不同的大小(非常有利于性能),可以提前停止

答案 1 :(得分:2)

       File dir = Environment.getExternalStorageDirectory();

       File yourFile1 = new File(dir, "path/to/the/file/inside/the/textfile1.txt");
       File yourFile2 = new File(dir, "path/to/the/file/inside/the/textfile2.txt");

       put the check for file exists ..........

       FileInputStream fstream1 = new FileInputStream(yourFile1 );  
       FileInputStream fstream2 = new FileInputStream(yourFile2 );  

     DataInputStream in1 = new DataInputStream(fstream1);  
      BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));  

    DataInputStream in2 = new DataInputStream(fstream2);  
      BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));  

    String strLine1, strLine2;  
     boolean isSame = true;
    while ((strLine1 = br1.readLine()) && strLine2 = br2.readLine()) ) != null)   {  
          if(strLine1.equals(strLine2))  
               System.out.println(strLine1)
          else{                     //optional just try to optimize can remove
                  //not same 
                  isSame = false;
                   break;
                }  
    }