0

I'd like to know what can I do to print 3 strings (let's say a string array), to a .txt file in android. (e.g. line 1: "red", line 2 : "blue", line 3: "green").

Also, I'd like to check first if that file exists, in case it does, do nothing, otherwise create it with the three colors in the separate lines.

kingdango
  • 3,979
  • 2
  • 26
  • 43
Alexander
  • 107
  • 1
  • 2
  • [Android documentation](http://developer.android.com/guide/topics/data/data-storage.html) has lots of information and samples on how Apps can save files. – adelphus Aug 08 '15 at 19:10

2 Answers2

1

To create a file with three colors on separate lines:

ArrayList<String> colors = new ArrayList<String>();
colors.put("red");
colors.put("blue");
colors.put("green");

File file= new File(root, filename);
FileWriter writer = new FileWriter(file);
for (String color : colors) {
    writer.append(color);
    writer.append("\n");
}
writer.flush();
writer.close();
androholic
  • 3,633
  • 3
  • 22
  • 23
  • That goes into internal storage? where says root, should i leave it like that or change something? Finally (im unfamiliar with android), what should i do to read that file and store the different lines in an array? – Alexander Aug 08 '15 at 19:38
  • root is dir/dir path. It is up to you where you want to store the file. – androholic Aug 08 '15 at 19:43
  • To read a file: http://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android – androholic Aug 08 '15 at 19:44
  • but if i wanna save it in the internal storage, should i leave root, or change something? – Alexander Aug 08 '15 at 19:48
  • Replace root with getFilesDir() or getCacheDir() for internal storage. – androholic Aug 08 '15 at 19:50
0

The best way to do this is to create a separate class called Files and use that class to manage all internal files. This will be helpful as you will not have to repeatedly write long blocks of code each time you want to read or write to an internal file.

1) Create a new Class. In Android Studio, right click over your MainActivity class on the left, and click on New --> Java Class. Name this class Files.

2) Remove all the code except for the first line (it starts with "package") and paste the code below.

import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

public class Files {

Context context;

public Files(Context context){
    this.context = context;
}

public void clear(final String path){
    File dir = context.getFilesDir();
    File files = new File(dir, path);
    boolean deleted = files.delete();
}

public void write(final String path, final String[] text){
    write(path, text[0]);
    for(int i=1; i<text.length; i++){
        append(path, text[i]);
    } 
}

public void append(final String path, final String[] text){
    for(String s : text){
        append(path, s);
    } 
}

public String[] read(final String path){
    ArrayList<String> list = readArr(path);
    return list.toArray(new String[list.size()]);
}

public void append(final String path, final String text){
    FileOutputStream outputStream;
    try {
        outputStream = context.openFileOutput(path, Context.MODE_APPEND);
        if(!read(path).isEmpty()){
            outputStream.write(System.getProperty("line.separator").getBytes());
        }
        outputStream.write(text.getBytes());
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
public void write(final String path, final String text){
    FileOutputStream outputStream = null;
    try {
        outputStream = context.openFileOutput(path, Context.MODE_PRIVATE);

        outputStream.write(text.getBytes());
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public ArrayList<String> readArr(String path){
    ArrayList<String> text = new ArrayList<String>();

    FileInputStream inputStream;
    try {
        inputStream = context.openFileInput(path);

        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(isr);

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            text.add(line);
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return text;
}

public boolean isEmpty(final String path){
    return (readArr(path).size()==0);
}

}

In your MainActivity class, create an instance of Files in the onCreate method:

Files file = new Files(this);

Now, you can use all of the methods in the Files class. Here is what they do:

String path = "example.txt";                      //This is where the data will go
String[] exampleArrayOne = {"red", "green", "blue"}; 
String[] exampleArrayTwo = {"purple", "orange", "indigo"}; 

file.clear(path);                                 //Clears a file
boolean isEmpty = file.isEmpty(path);             //Will be true if the file is empty, 
                                                  //otherwise false

file.write(path, "pink");                         //Will clear the file and write pink on 
                                                  //the first line  

file.write(path, exampleArrayOne);                //Will clear the file and write the array, 
                                                  //each element on a new line

file.append(path, "yellow");                      //Will NOT clear the file and will add
                                                  //"yellow" to the next empty line

file.append(path, exampleArrayTwo);               //Will NOT clear the file and will add
                                                  //each element of the array to an empty 
                                                  //line

Make sure that you know the difference between the write(path, array) and the append(path, array) methods. write(path, array) will clear the file and overwrite it, while append(path, array) will add to the existing file.

To read from a file, read(path) will return a String[];

String[] fileText = file.read(path);

Lastly, to check if a file exists, otherwise add it, you would do this:

String path = "whateverYouLike.txt";
String[] colors = {"red", "green", "blue"};

//If the file is empty, write the array to it
if(file.isEmpty(path)){
    file.append(path, colors);
}