Reputation: 229
So I have a collection of phrases that are separated by newlines and I would like to populate an array with these phrases. This is what I have so far:
Scanner s;
s = new Scanner(new BufferedReader(new FileReader("Phrases.txt")));
for(i = 0; i < array.length;i++)
{
s.nextLine() = array[i];
}
Is there a fast and simple way to just populate an array with phrases separated by newlines?
Upvotes: 3
Views: 4218
Reputation: 32343
Don't waste your time with Scanner
. BufferedReader
is just fine. Try this:
BufferedReader br = new BufferedReader(new FileReader("Phrases.txt")));
LinkedList<String> phrases = new LinkedList<String>();
while(br.ready()) {
phrases.add(br.readLine());
}
String[] phraseArray = phrases.toArray(new String[0]);
By the way it's important to use LinkedList
not ArrayList
if the file is large. That way you only create one array at the end. Otherwise you will have a lot of large array creation and wasted memory.
Upvotes: 1
Reputation: 178521
It can be done with a 1 liner with apache commons and specifically FileUtils.readLines()
FileUtils.readLines(myFile).toArray(new String[0]);
Upvotes: 1
Reputation: 1432
You have the assignment operation inverted (array[i]
should be set to s.nextLine()
, not the other way around. Also, it would be best to modify the for loop to terminate when no more lines exist:
for(i = 0; i < array.length && s.hasNextLine() ;i++) {
array[i] = s.nextLine()
}
Upvotes: 1
Reputation: 272417
Since you don't know how many phrases you're likely to have (I suspect), I would populate an ArrayList<String>
and convert it to an array using ArrayList.toArray() once you're done. I'd perhaps keep it as a Java collection, however, for greater flexibility.
Upvotes: 1
Reputation: 213391
The assignment should be reverse: -
array[i] = s.nextLine();
And, I think you should fill your array based on the input received from the file. Here you are receving input based on the length of your pre-declared array. I mean, since you are using an array
, your size is fixed. So you can only populate it with a fixed number of phrases.
A better way would be to use an ArrayList
.
List<String> phrases = new ArrayList<String>();
Now, you can populate your arraylist, based on the phrases you get from your file. You don't need to pre-define the size. It increases in size dynamically.
And to add phrases, you would do: -
phrases.add(s.nextLine());
With a while
loop to read till EOF
.
while (s.hasNextLine()) {
phrases.add(s.nextLine());
}
Upvotes: 4
Reputation: 46428
you are doing it wrong. it has to be
for(i = 0; i < array.length;i++)
{
array[i]=s.nextLine();
}
array[i] = value; // the value would be assigned into the array at index i.
However, a better option would be to use a List implementing classes such as ArrayList which gives you an advantage of dynamic size.
List<String> list = new ArrayList<>();
list.add(s.nextLine(());
Upvotes: 0