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
You need to do something like this for your case:-
int i = 0;
while((str = in.readLine()) != null){
arr[i] = str;
i++;
}
But note that the arr
should be declared properly, according to the number of entries in your file.
Suggestion:- Use a List
instead(Look at @Kevin Bowersox post for that)
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
I would recommend using an ArrayList
, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());
Just use Apache Commons IO
List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
This should work because it uses List as you don't know how many lines will be there in the file and also they may change later.
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
lines.add(str);
}
String[] linesArray = lines.toArray(new String[lines.size()]);