2012-06-06 108 views
1

可能重複:
Compare the content of 2 text files in java language文本字符串比較文件

我想比較兩個.txt文件串在Android應用程序。你能告訴我如何進行? 我想插入代碼這個

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

如此簡單轉換成字符串兩個文件,並使用equals比較字符串... –

+0

你想不比較兩個文件但找到兩個文件中相同的文本的一部分? – Arseniy

+0

不,我希望兩個文件中都不相似的部分 – user1437027

回答

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; 
       } 
    } 
+1

看起來不錯。此外,我建議使用AsyncTask進行此操作以避免阻塞UI線程。 – Arseniy

4

你不應該閱讀整個文件到內存中,然後對它們進行比較!

您可以分塊讀取兩個文件,比較每個塊對,如果塊不同,則停止讀取。你也應該重用塊的內存緩衝區。

這種方法讓你提前終止(良好性能)和管理內存(這樣你可以比較非常大的文件)

記住,這是耗時的操作,所以你不應該在UI線程做。爲此使用AsyncTask

另外,我建議你到讀取文件之前比較文件大小。這是非常快的,讓您在文件的情況下,很早就停止有不同的尺寸(性能非常不錯)

+0

+1在我的新答案我試着做同樣的事情......是不是? –

+1

+1,立即閱讀完整文件是矯枉過正。我不知道這是否適用於Android,但公共-io的具有輔助類來做到這一點:http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#contentEquals %28java.io.File,%20java.io.File%29個 – ftr

+0

公地IO可到Android,所以真的好習慣重用這個代碼 – Arseniy