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/..
」
android設備可能有一個名爲'External storage'的模擬SD卡。你可以在那裏讀寫文件。什麼是你的Android設備?至少哪個版本的Android? –