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
When you do str = in.readLine()) != null
you read one line into str
variable and if it's not null execute the while
block. You do not need to read the line one more time in arr[i] = in.readLine();
. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> output = new LinkedList<String>();
while((str = in.readLine()) != null){
output.add(str);
}
String[] arr = output.toArray(new String[output.size()]);
You can use this full code for your problem. For more details you can check it on appucoder.com
class FileDemoTwo{
public static void main(String args[])throws Exception{
FileDemoTwo ob = new FileDemoTwo();
BufferedReader in = new BufferedReader(new FileReader("read.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str =in.readLine()) != null ){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println(" "+Arrays.toString(stringArr));
}
}
Try this:
String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)
arr[i++] = str;
System.out.println(Arrays.toString(arr));
Suggest use Apache IOUtils.readLines for this. See link below.
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
You can use this code. This works very fast!
public String[] loadFileToArray(String fileName) throws IOException {
String s = new String(Files.readAllBytes(Paths.get(fileName)));
return Arrays.stream(s.split("\n")).toArray(String[]::new);
}