将字符串写入Assets文件夹中的文件

时间:2017-04-03 11:19:55

标签: java android bufferedwriter

我的.txt file文件夹中有一个Assets。 我试过用                     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getAssets().open("---.txt")));

我收到错误,强调(getAssets().open("---.txt"))); Saying

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

我不知道如何写这个文件,我需要帮助。如果我知道如何擦除已存在于该文件中的所有内容并写入空白文件中也很好...(很抱歉不清楚)。

我知道我可以在PC上使用PrintWriter执行此操作,但我现在正在学习Android

2 个答案:

答案 0 :(得分:2)

您无法将任何文件写入资产或任何原始目录。

它将位于Android文件系统中的哪个位置。因此,请将您的txt文件写入内部OR外部存储器。

答案 1 :(得分:0)

assets文件夹是只读的,以及它的内容。如果您希望修改和保存资产中的任何修改,请考虑使用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));