Android Studio:将文件加载到数组中

时间:2016-01-19 00:07:36

标签: java android android-studio

我创建了一个可以将数组保存到文件的类,但是,我需要它将文件加载回名为SampleGridViewAdapter的Activity内部的数组中。

名为gallerydump_img.txt的文本文件格式:

https://mywebsite.com/path/samplefile.rtf
https://anotherwebsite.com/
https://thirdwebsite.com/example/

我尝试了strings = LIST[i]strings是文件的输出,i是循环,LIST是输出文件数据的数组,逐行。更多代码如下:

@Override
    protected void onPostExecute(String[] strings) {

        for(int i = 0; i < strings.length; i++) {
            Log.e("GalleryFileDump", strings[i]);
            ArrayToFile.writeArrayToFile(strings, Environment.getExternalStorageDirectory() + "/gallerydump_img.txt", "Eww, errors. Want a cookie? :: Unable to write to file gallerydump.bin. Check the report below for more information. :)");
            strings = LIST[i]
        }
    }

任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

这是您想要阅读

的内容
public static List<String> readLines() {
    File f = new File("gallerydump_img.txt");
    BufferedReader r;
    List<String> lines = new ArrayList<String>();
    try {
        r = new BufferedReader(new FileReader(f));
        String line;
        while (true) {
            if ((line = r.readLine()) == null)
                break;
            lines.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace(); // file not found
    }
    return lines;
}

这就是你想要

public static void writeLines(List<String> lines) {
    File f = new File("gallerydump_img.txt");
    try {
        PrintWriter pw = new PrintWriter(f);
        for (String line : lines)
            pw.println(line);
        pw.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace(); // file not found
    }
}

答案 1 :(得分:0)

我猜你上面有什么不编译?如果没有,这很好。我只是想确定我理解这个问题。

无论如何,将字符串序列化和反序列化为文件的一种方法如下:

String[] readFile(String filename)
{
    String[] strings;

    BufferedReader reader = null;
    try
    {
        reader = new BufferedReader( new InputStreamReader( new FileInputStream(filename)));

        String str = reader.readLine();
        while( null != str )
        {
            strings.add(str);
            str = reader.readLine();
        }
    }
    catch( IOException e )
    {
        e.printStackTrace();
    }

    if( null != reader )
    {
        reader.close();
    }
    return strings.toArray(new String[strings.size()]);
}


void writeFile(String filename, String[] strings )
{
    PrintWriter writer = null;

    try
    {
        writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename)));

        for( int idx = 0; idx < strings.length; idx++ )
        {
            writer.println(strings[idx]);
        }
    }
    catch( IOException e )
    {
        e.printStackTrace();
    }

    if( null != writer )
    {
        writer.close();
    }

}