2017-04-03 65 views
0

我的Assets文件夾中有.txt file。 我嘗試使用 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getAssets().open("---.txt")));將字符串寫入資產文件夾中的文件

我得到一個錯誤,強調(getAssets().open("---.txt")));

OutputStreamWriter(java.io.OutputStream) in OutputStreamWriter cannot be applied to (java.io.InputStream)

我不知道該怎麼寫這個文件,我需要幫助。如果我知道如何擦除該文件中已經存在的所有內容並寫入一個空白文件,這也是一件好事情......(對不清楚)。

我知道我可以在PC上使用PrintWriter來做到這一點,但我現在正在學習Android

回答

2

您無法將任何文件寫入資產或任何原始目錄。

它位於Android文件系統的位置。因此,請將您的txt文件寫入內部或外部存儲器。

0

資產文件夾是隻讀的,以及其內容。如果您希望修改和保存資產的任何修改,請考慮使用Context.openFileOutput()將副本存儲在設備存儲中。這裏是一個沒有異常處理的例子:

// copy the asset to storage 

InputStream assetIs = getAssets().open(filename); 
OutputStream copyOs = openFileOutput(filename, MODE_PRIVATE); 

byte[] buffer = new byte[4096]; 
int bytesRead; 

while ((bytesRead = assetIs.read(buffer)) != -1) { 
    copyOs.write(buffer, 0, bytesRead); 
} 

assetIs.close(); 
copyOs.close(); 

// now you can open and modify the copy 

copyOs = openFileOutput(filename, MODE_APPEND); 

BufferedWriter writer = 
     new BufferedWriter(
       new OutputStreamWriter(copyOs)); 
相關問題