简体   繁体   中英

Reading txt file contents and storing in array

I have been trying to read a txt file. The txt file contains lines eg

First Line
Second Line
Third Line
.
.
.

Now I am using following code

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

My question is, how can i store each line in the arrayList. Ofc We have to use a check for "/n" but how.

You could alternatively use the Scanner class.

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

You don't have to worry about \\n , since Scanner.nextLine() will skip the newline.

This code should work.

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

This:

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

}

Should probably look more like this:

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

Since you are using a BufferedReader , you should be calling readLine() instead of reading into a char buffer. The Reader declaration also needs to be BufferedReader .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM