简体   繁体   English

使用FileWriter编辑文件

[英]Editing a file using FileWriter

I am trying to Edit a existing file which is in my R.raw folder i am able to read the file but when i run the write function it is not working . 我正在尝试编辑R.raw文件夹中的现有文件,但我能够读取该文件,但是当我运行写入功能时,它无法正常工作。

    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();
          }
       }

i even tried 我什至尝试过

fw = new FileWriter(file,true); fw =新的FileWriter(file,true);

if i add toast between even line it seems to get stuck at 如果我在偶数行之间添加吐司,似乎会卡在

fw = new FileWriter(fw); fw =新的FileWriter(fw);

You can't able to Write 你不能写

As @CommonsWare said you can't write on resources but you could use internal storage using openFileOutput and openFileInput and BufferedReaders and BufferedWriters. 正如@CommonsWare所说,您不能写资源,但是可以使用openFileOutput和openFileInput以及BufferedReaders和BufferedWriters使用内部存储。 You can check it here 你可以在这里检查

from the answer of @rodkarom in the following link 从以下链接中@rodkarom的答案

Write to a Text File Resource in Android 在Android中写入文本文件资源

and @Andro Selva says same thing in the following link @Andro Selva在以下链接中说了同样的话

How to write a file in Android to the raw folder? 如何在Android中将文件写入原始文件夹?

you can able to read the content from the textfile which is present in the res/raw folder dude 您可以从res / raw文件夹dud​​e中存在的文本文件中读取内容

read the file from res folder 从res文件夹中读取文件

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();
      }

check it and inform 检查并告知

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM