读取文本文件内容并存储在数组中

时间:2012-08-12 00:18:34

标签: java android eclipse

我一直在尝试读取txt文件。 txt文件包含例如

的行
First Line
Second Line
Third Line
.
.
.

现在我正在使用以下代码

InputStream is = null;
try {
    is = getResources().getAssets().open("myFile.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
    e.printStackTrace();
}

ArrayList<String> arrayOfLines = new ArrayList<String>();

Reader reader;
//char[] buffer = new char[2048];
try {
    Reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    int n;
    while   ((n = reader.read()) != -1) {

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

我的问题是,我如何在arrayList中存储每一行​​。 Ofc我们必须使用"/n"检查但是如何。

3 个答案:

答案 0 :(得分:2)

您也可以使用Scanner类。

Scanner in = new Scanner(new File("/path/to/file.txt"));
while(in.hasNextLine()) {
    arrayOfLines.add(in.nextLine());
}

Scanner.nextLine() will skip the newline.

以来,您无需担心\n

答案 1 :(得分:2)

此代码应该有效。

 ArrayList<String> arrayOfLines = new ArrayList<String>();
 FileInputStream fstream = new FileInputStream("myfile.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  while ((strLine = br.readLine()) != null)   {
  arrayOfLines.add(strLine);
  }

答案 2 :(得分:0)

此:

int n;
while   ((n = reader.read()) != -1) {

}

应该看起来更像这样:

String line = reader.readLine();
while   (line!=null) {
    arrayOfLines.add(line);
    line = reader.readLine();
}

由于您使用的是BufferedReader,因此您应该调用readLine()而不是读取char缓冲区。 Reader声明也必须为BufferedReader

相关问题