Create an Array populating it by .txt elements
13,488
Solution 1
- Wrap a
BufferedReader
around aFileReader
so that you can easily read every line of the file; - Store the lines in a
List
(assuming you don't know how many lines you are going to read); - Convert the
List
to an array usingtoArray
.
Simple implementation:
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
Solution 2
This smells like homework. If it is you should re-read your notes, and tell us what you've tried.
Personally, I would use a Scanner (from java.util).
import java.io.*;
import java.util.*;
public class Franky {
public static void main(String[] args) {
Scanner sc = new Scanner(new File("myfile.txt"));
String[] items = new String[3]; // use ArrayList if you don't know how many
int i = 0;
while(sc.hasNextLine() && i < items.length) {
items[i] = sc.nextLine();
i++;
}
}
}
Author by
Fseee
Updated on June 04, 2022Comments
-
Fseee almost 2 years
I want to create an array, populating it while reading elements from a .txt file formatted like so:
item1 item2 item3
So the final result has to be an array like this:
String[] myArray = {item1, item2, item3}
Thanks in advance.