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...
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.
Using nio packages exposed by Java 8, you can write an InputStream to a File using Files. copy() utility method.
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.
You are iterating twice in each loop
String line;
while ((line=r.readLine()) != null) {
myDict.add(line);
}
Using Apache IOUtils:
List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With