0
我正在嘗試將每個訪問URL
保存在.txt
文件中。它工作正常,但是,每個新的URL
替換舊的。如何將字符串添加到文本文件?
1)如何添加URL(頂部,而不是底部)?
2)如何在每個URL之間添加一行空格?
MainActivity.java
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
// don't hide URLBar on welcome screen
// save to history.txt
HistoryHelper file = new HistoryHelper(view.getContext());
file.writeToSD(url.toString());
}
HistoryHelper.java
public class HistoryHelper {
String TAG = "MyFile";
Context context;
public HistoryHelper(Context context) {
this.context = context;
}
public Boolean writeToSD(String text) {
Boolean write_successful = false;
File root = null;
try {
// check for SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG, "path.." + root.getAbsolutePath());
// check sdcard permission
if (root.canWrite()) {
File fileDir = new File(
Environment.getExternalStorageDirectory() + "/AVD/");
fileDir.mkdirs();
File file = new File(fileDir, "History.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
Toast.makeText(context, "success!", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
Log.e("ERROR:---",
"Could not write file to SDCard" + e.getMessage());
write_successful = false;
Toast.makeText(context, "operation failed!", Toast.LENGTH_LONG)
.show();
}
return write_successful;
}
}
什麼是「磁盤I/O開銷」? – Cassie
對於每個訪問的URL,您都會創建一個historyHelper的新對象並每次打開文件,因此請嘗試使用一個對象並僅使用該參考 –
我在哪裏添加此代碼? – Cassie