我正在尝试将每个访问过的URL
保存在.txt
文件中。它工作正常,但是,每个新的URL
都会替换旧的@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());
}
。
1)如何添加网址(在顶部,不在底部)?
2)如何在每个网址之间添加一行空格?
MainActivity.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;
}
}
HistoryHelper.java
{{1}}
答案 0 :(得分:1)
以附加模式打开文件
FileWriter fileWriter = new FileWriter (file, true) ;
使用BufferedWriter,每次访问URL时都要打开文件。尽量减少磁盘I / O开销。