Reputation: 223
I am trying to save each visited URL
in a .txt
file. It works fine, however, every new URL
replaces the older one.
1) How do i add URL's (on top, Not bottom) ?
2) How do i add a one line space between each 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;
}
}
Upvotes: 0
Views: 71
Reputation: 104
Open file in append mode
FileWriter fileWriter = new FileWriter (file, true) ;
Use BufferedWriter, you are opening file each time when URL get accessed. Try to minimise disk i/O overhead.
Upvotes: 1