简体   繁体   中英

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 .

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

if i add toast between even line it seems to get stuck at

fw = new 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. You can check it here

from the answer of @rodkarom in the following link

Write to a Text File Resource in Android

and @Andro Selva says same thing in the following link

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

you can able to read the content from the textfile which is present in the res/raw folder dude

read the file from res folder

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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