Alexander
Alexander

Reputation: 107

How to write a txt file in different lines using android

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.

Upvotes: 0

Views: 3793

Answers (2)

Arjun Panickssery
Arjun Panickssery

Reputation: 183

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

Upvotes: 0

androholic
androholic

Reputation: 3663

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

Upvotes: 1

Related Questions