2016-11-08 8 views
0

txtファイルにAndroid appendを使用しようとしています。 appendメソッドはユニットテストに合格することができません。Android appendファイルは単体テストに合格できません

例:

私は二回 "123456123456" を取得するには "123456" を追加しようとしましたが、私はエラーました:私の質問は<> []の意味は<123456[]><123456[123456]>に何である

junit.framework.ComparisonFailure: expected:<123456[]> but was:<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

アンドロイドデバイスには、「外部ストレージ」と呼ばれるエミュレートされたSDカードがある可能性があります。そこにファイルを読み書きすることができます。あなたのアンドロイドデバイスは何ですか?少なくともAndroidのどのバージョンですか? –

答えて

0

変更

FileOutputStream fOut = new FileOutputStream(filePath); 

FileOutputStream fOut = new FileOutputStream(filePath, true); 

への2番目のパラメータが追加か意味のような今のパスです。

アペンドのための別の方法は次のとおりです。

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

Context.MODE_APPENDモードが存在しないか、いないファイルをチェックします。そうでなければ、ファイルを作成し、最後に追加します。

関連する問題