How do I write to a .txt file in Android?

后端 未结 2 688
长情又很酷
长情又很酷 2020-12-09 18:29

I have an app that needs to read and write to a text file. I have it reading, but I don\'t have it writing. The idea is that when I click the save button on the screen, its

相关标签:
2条回答
  • 2020-12-09 19:03

    with mari's solution i was getting

           java.lang.IllegalArgumentException: contains a path separator
    

    then i tried following and it worked for me

      File root = new File(DIRECTORY_PATH);
      File gpxfile = new File(root, "samples.txt");
      FileWriter writer = new FileWriter(gpxfile);
      writer.append("First string is here to be written.");
      writer.flush();
      writer.close();
    

    you can loop it to write multiple lines

    0 讨论(0)
  • 2020-12-09 19:08

    You can use FileOutputStream instead of OutputStreamWriter, something like this:

    File file = getFileStreamPath("test.txt");
    
    if (!file.exists()) {
       file.createNewFile();
    }
    
    FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
    
    for (String string: data){
        writer.write(string.getBytes());
        writer.flush();
    }
    
    writer.close();
    

    Check the android docs.

    0 讨论(0)
提交回复
热议问题