Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading InputStream to Arraylist

I have to read a dict.txt file which contains one string for line and add these to an arraylist.

I tried this:

public ArrayList<String> myDict = new ArrayList<String>();

InputStream is = (getResources().openRawResource(R.raw.dict));
BufferedReader r = new BufferedReader(new InputStreamReader(is));
try {
    while (r.readLine() != null) {
        myDict.add(r.readLine());
    }  
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

but something wrong...

like image 670
Edoardo Balestra Avatar asked Dec 16 '11 09:12

Edoardo Balestra


People also ask

How do I read a text File into an ArrayList?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.

Can we convert InputStream to File in Java?

Using nio packages exposed by Java 8, you can write an InputStream to a File using Files. copy() utility method.

How do you create an input stream object to read a File?

Java FileInputStream constructorsFileInputStream(File file) — creates a file input stream to read from a File object. FileInputStream(String name) — creates a file input stream to read from the specified file name. FileInputStream(FileDescriptor fdObj) — creates a file input read from the specified file descriptor.


2 Answers

You are iterating twice in each loop

String line;
while ((line=r.readLine()) != null) {
    myDict.add(line);
}
like image 163
rds Avatar answered Sep 21 '22 14:09

rds


Using Apache IOUtils:

List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
like image 32
yurin Avatar answered Sep 23 '22 14:09

yurin