Search code examples
javaandroidiofileoutputstream

Android adding multiple lines to file internal stroage


I have a simple game app that has 3 place scoreboard and I need to save the data. I'm not sure whether I should be saving this on external or internal storage. I have managed to save a csv file in external but when testing I found it deosnt work on all devices. I am now looking at saving the data on internal storage and looking at the following standard file saving code.

String FILE_NAME = "file.txt";
    try {
        FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(someText.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}  

The class doesnt provide any nextLine() method.

My question is should I use external or internal storage, and if im using internal storage how can I seperate each line?


Solution

  • Writing:

    String FILE_NAME = "file.txt";
    try {
        FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
        PrintWriter writer = new PrintWriter( new OutputStreamWriter( fos ) );
        writer.println(someText.toString());
        writer.println(someOtherText.toString());
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }  
    

    Reading:

    String FILE_NAME = "file.txt";
    try {
        FileInputStream fis = openFileInput(FILE_NAME, Context.MODE_PRIVATE);
        BufferedReader reader = new BufferedReader( new InputStreamReader( fis ) );
        String line;
        while ( (line = reader.readLine()) != null ) {
            System.out.println("Read line: " + line);
        } 
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }