2012-08-12 125 views
1

我一直在尝试读取一个txt文件。 TXT文件包含的行e.g读取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"但是如何。

回答

2

您也可以使用Scanner类。

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

您不必担心\n,因为Scanner.nextLine() will skip the newline.

+0

它存储的话不仅没有全线。 – 2012-08-12 00:27:58

+0

我的错误。检查编辑。 – Makoto 2012-08-12 00:28:48

0

此:

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

} 

应该看起来可能是这样的:

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

由于您使用的是BufferedReader,你应该叫readLine(),而不是读成字符缓冲区。 Reader声明还需要BufferedReader

+0

的readLine是未定义类型读者 – 2012-08-12 00:23:43

+0

@umar你需要改变你的'读者reader'成'的BufferedReader reader' – 2012-08-12 00:25:16

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