如何使用android在不同的行中编写txt文件

时间:2015-08-08 19:07:02

标签: android arrays string printing lines

我想知道如何将3个字符串(假设是一个字符串数组)打印到android中的.txt文件中。 (例如第1行:“红色”,第2行:“蓝色”,第3行:“绿色”)。

此外,我想首先检查该文件是否存在,如果存在,则不执行任何操作,否则使用单独行中的三种颜色创建它。

2 个答案:

答案 0 :(得分:1)

要在不同的行上创建三种颜色的文件:

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

答案 1 :(得分:0)

执行此操作的最佳方法是创建一个名为Files的单独类,并使用该类管理所有内部文件。这将非常有用,因为每次要读取或写入内部文件时都不必重复编写长代码块。

1)创建一个新类。在Android Studio中,右键单击左侧的MainActivity类,然后单击New - &gt; Java类。将此类命名为Files。

2)删除除第一行以外的所有代码(以&#34; package&#34;开头)并粘贴下面的代码。

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

}

在MainActivity类中,在onCreate方法中创建一个Files实例:

Files file = new Files(this);

现在,您可以使用Files类中的所有方法。以下是他们的所作所为:

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

确保您知道写入(路径,数组)追加(路径,数组)方法之间的区别。 写入(路径,数组)将清除文件并覆盖它,而追加(路径,数组)将添加到现有文件中。

要从文件中读取,读取(路径)将返回String [];

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

最后,要检查文件是否存在,否则添加它,您可以这样做:

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