all,I'm now facing the problem of no idea on storing the content in text file into the array. The situation is like, text file content:
abc1
xyz2
rxy3
I wish to store them into array line by line, is that possible? What I expect is like this:
arr[0] = abc1
arr[1] = xyz2
arr[2] = rxy3
I've try something like this, but seem like not work for me. If anyone can help me, really thanks a lot.
The code is:
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
while((str = in.readLine()) != null){
String[] arr = str.split(" ");
for(int i=0 ; i<str.length() ; i++){
arr[i] = in.readLine();
}
}
In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.
You can store multiple pieces of text in a string array. Each element of the array can contain a string having a different number of characters, without padding.
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.
The simplest solution:
List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]);
Note that java.nio.file.Files is since 1.7
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