将文本文件读取到数组列表

时间:2018-03-15 12:19:24

标签: java android

我几个星期以来一直坚持这个问题但没有用。 我将数组列表的内容保存到文本文件中,以便在用户打开活动时,数组列表会为用户加载自身。

当我尝试读取文本文件并将内容添加到数组列表时,我在arraylist“Java.io.ObjectInputStream@b37391”中获得以下输入

我的数组列表将如下所示 [你好,leon,java.io.ObjectInputStream @ b373791]

如何从文本文件中读取文本并在数组列表中显示其内容

我提供了下面使用的代码,我已经阅读了很多教程和stackoverflow问题,但似乎没有任何效果。一些建议将不胜感激。

  try {
     File f = new File(getFilesDir(), "anxfile.txt");
     FileInputStream readtheting = new FileInputStream(f);
     ObjectInputStream ois = new ObjectInputStream(readtheting);

     ois.readObject();

     arrayList.add(String.valueOf(ois));

     adapter.notifyDataSetChanged();
     ois.close();

  } catch (FileNotFoundException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  } catch (ClassNotFoundException e) {
     e.printStackTrace();
  }

2 个答案:

答案 0 :(得分:0)

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

导入后,然后:

public class ReadFile{

   public static void main(String[] args){

      try {
        BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tmotswagole\\My Documents\\Example.txt"));
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = reader.readLine()) != null) 
        {
            lines.add(line);
        }
        reader.close();
          for (int i =0; i<lines.size(); i++) {
            String[] items = lines.get(i).split("", 1);
            for (String s: items) {
                System.out.println(s);
            }
           }

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

}

这就是你完全执行该代码的方法

答案 1 :(得分:0)

你可以用它来阅读:

List<String> strings = Files.readAllLines(new File(getFilesDir(), "anxfile.txt").toPath());

这个写作:

Files.write(new File(getFilesDir(), "anxfile.txt").toPath(), <someArray>);