首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用FileWriter编辑文件

使用FileWriter编辑文件
EN

Stack Overflow用户
提问于 2014-07-02 20:06:55
回答 1查看 323关注 0票数 0

我正在尝试编辑在我的R.raw文件夹中的现有文件,我能够读取该文件,但当我运行写入功能时,它不工作。

代码语言:javascript
复制
    public void tofile(View v){ 
        BufferedWriter bw=null;
        FileWriter fw =null;
        try {
            String path = ("/Page2/res/raw/text.txt");
            File file = new File(path);
            fw = new  FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("hello");
            bw.flush();
            bw.close();   
          } catch (IOException e) {
            e.printStackTrace();
          }
       }

我甚至试过

fw =新文件(FileWriter,true);

如果我在偶数行之间添加吐司,它似乎会卡住

fw =新的FileWriter(fw);

EN

回答 1

Stack Overflow用户

发布于 2014-07-07 12:53:34

你不会写字

正如@CommonsWare所说,你不能写资源,但是你可以通过openFileOutput和openFileInput,BufferedReaders和BufferedWriters来使用内部存储。你可以在这里查看

来自以下链接中@rodkarom的答案

Write to a Text File Resource in Android

@Andro Selva在下面的链接中说了同样的话

How to write a file in Android to the raw folder?

您可以从res/raw文件夹dude中的文本文件中读取内容

从res文件夹读取文件

代码语言:javascript
复制
public String readStringFromResource(Context ctx, int resourceID) {
        StringBuilder contents = new StringBuilder();
        String sep = System.getProperty("line.separator");

        try {           
          InputStream is = ctx.getResources().openRawResource(R.raw.trails);

          BufferedReader input =  new BufferedReader(new InputStreamReader(is), 1024*8);
          try {
            String line = null; 
            while (( line = input.readLine()) != null){
              contents.append(line);
              contents.append(sep);
            }
          }
          finally {
            input.close();
          }
        }
        catch (FileNotFoundException ex) {
            Log.e(TAG, "Couldn't find the file " + resourceID  + " " + ex);
            return null;
        }
        catch (IOException ex){
            Log.e(TAG, "Error reading file " + resourceID + " " + ex);
            return null;
        }

        return contents.toString();
      }

检查并通知

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24530714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档