2016-06-28 107 views
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; 
    } 
} 

回答

1
追加模式

打開文件

FileWriter fileWriter = new FileWriter (file, true) ; 

使用的BufferedWriter,您就可以在每次打開文件URL ge訪問。儘量減少磁盤I/O開銷。

+0

什麼是「磁盤I/O開銷」? – Cassie

+0

對於每個訪問的URL,您都會創建一個historyHelper的新對象並每次打開文件,因此請嘗試使用一個對象並僅使用該參考 –

+0

我在哪裏添加此代碼? – Cassie

相關問題