I have a long local text file and I would like to write a method that will read it and add the first word of each line into an ArrayList
of Strings
.
I have a very primitive understanding of basic I/O operations. Right now, from what I understand, I would need to have some kind of InputReader
object read each first word and then use something like an OutputStreamBuffer
to add each of those words as Strings
to the ArrayList
in turn. Am I on the right track?
If that is correct, I'm not exactly sure what the correct syntax would be to do it (especially with having the InputStreamReader
go to the next line after copying the first word in each line. If I'm not even close, what would you guys do?
Thanks a lot for your help everyone. I hope my description was clear enough for you.
You're on the right track - here's my general suggestion for your requirement...
ArrayList<String>
for storing your words BufferedReader
to read from your file line-by-line using readLine();
String.split()
method or a StringTokenizer
or a regex expression) ArrayList
using an add()
method and then read the next line from point 2. There shouldn't be a need to use an OutputStream
for your ArrayList
, thats just complicating things.
I'd use java.util.Scanner
, specifically the hasNextLine and nextLine methods to get each line.
Then use another scanner on each line and the hasNext and next methods to get the first word, or use the String split method (or some other way) to get the first word.
Then add the first word into the ArrayList<String>
.
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.