2016-11-08 16 views
0

我想在android文件上使用android append。 append方法無法通過單元測試。Android追加文件無法通過單元測試

例如:

我想追加 「123456」 兩次獲得 「123456123456」,但我得到了錯誤:

junit.framework.ComparisonFailure: expected:<123456[]> but was:<123456[123456]> 

我的問題是什麼的<> []<123456[]><123456[123456]>意思?

我的測試方法如下,我能順利通過第一assertEqual

public void appendFileCorrect() throws Exception { 
      String contentToWrite = "123456"; 
      Context appContext = InstrumentationRegistry.getTargetContext(); 
      FileManager manager = new FileManager("jim11.txt"); 
      manager.append(contentToWrite); 
      String file = manager.readFromFile(appContext); 
      assertEquals(file, contentToWrite); 
      manager.append(contentToWrite); 
      String appendFile = manager.readFromFile(appContext); 
      assertEquals(appendFile, contentToWrite+contentToWrite); 
     } 

的到方法追加到文件的末尾:

public String append(String content) throws IOException { 

     try { 
      FileOutputStream fOut = new FileOutputStream(filePath); 
      OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
      myOutWriter.append(content); 
      myOutWriter.close(); 
      fOut.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return fileName; 
    } 

的方法,

public String readFromFile(Context context) throws IOException { 

     String ret = ""; 
     try { 
      FileInputStream inputStream = context.openFileInput(fileName); 
      if (inputStream != null) { 
       InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
       BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
       StringBuilder stringBuilder = new StringBuilder(); 
       String receiveString = ""; 
       while ((receiveString = bufferedReader.readLine()) != null) { 
        stringBuilder.append(receiveString); 
       } 
       inputStream.close(); 
       bufferedReader.close(); 
       ret = stringBuilder.toString(); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     return ret; 
    } 

另外我的Android設備沒有SD卡,任何我可以寫入公共場所的方式,我可以直接讀取文件?眼下的路徑是像 「data/data/files/..

+0

android設備可能有一個名爲'External storage'的模擬SD卡。你可以在那裏讀寫文件。什麼是你的Android設備?至少哪個版本的Android? –

回答

0

變化

FileOutputStream fOut = new FileOutputStream(filePath); 

FileOutputStream fOut = new FileOutputStream(filePath, true); 

第二個參數是指追加與否。

另一種方式爲追加爲:

outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);

Context.MODE_APPEND模式將檢查文件存在與否。如果沒有,則創建該文件並在最後附加。