I want read a text file into an array. How can I do that?
data = new String[lines.size]
I don\'t want to hard code 10 in the array.
<
you can do something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.text"));
int Counter = 1;
String line;
while ((line = reader.readLine()) != null) {
//read the line
Scanner scanner = new Scanner(line);
//now split line using char you want and save it to array
for (String token : line.split("@")) {
//add element to array here
System.out.println(token);
}
}
reader.close();
File txt = new File("file.txt");
Scanner scan = new Scanner(txt);
ArrayList<String> data = new ArrayList<String>() ;
while(scan.hasNextLine()){
data.add(scan.nextLine());
}
System.out.println(data);
String[] simpleArray = data.toArray(new String[]{});
If you aren't allowed to do it dtechs way, and use an ArrayList, Read it 2 times: First, to get the number of lines to declare the array, and the second time to fill it.
Use an ArrayList or an other dynamic datastructure:
BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();
while((String line = abc.readLine()) != null) {
lines.add(line);
System.out.println(data);
}
abc.close();
// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});
Use a List
instead. In the end, if you want, you can convert it back to an String[]
.
BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
data.add(s);
System.out.println(s);
}
abc.close();