【问题标题】:Write a String to a File in the Assets Folder将字符串写入资产文件夹中的文件
【发布时间】:2017-04-03 11:19:55
【问题描述】:

我的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

【问题讨论】:

    标签: java android bufferedwriter


    【解决方案1】:

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

    它将位于 Android 文件系统中的什么位置。因此,将您的 txt 文件写入内部或外部存储中。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-22
        • 2020-06-08
        • 2019-09-18
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 2011-10-24
        相关资源
        最近更新 更多