4

How to save text file content to different arrays?

my text file content is like this;

12 14 16 18 13 17 14 18 10 23
pic1 pic2 pic3 pic4 pic5 pic6 pic7 pic8 pic9 pic10
left right top left right right top top left right
100 200 300 400 500 600 700 800 900 1000

how can I save each line into different array? e.g.

line 1 will be saved in an array1
line 2 will be saved in an array2
line 3 will be saved in an array3
line 4 will be saved in an array4
Michael Petrotta
61.1k27 gold badges152 silver badges181 bronze badges
asked Mar 28, 2010 at 17:57

2 Answers 2

3

Solution 1

List<String[]> arrays = new ArrayList<String[]>(); //You need an array list of arrays since you dont know how many lines does the text file has
try {
 BufferedReader in = new BufferedReader(new FileReader("infilename"));
 String str;
 while ((str = in.readLine()) != null) {
 String arr[] = str.split(" ");
 if(arr.length>0) arrays.add(arr);
 }
 in.close();
 } catch (IOException e) {
 }

At the end arrays will contain every array. In your example arrays.length()==4

To iterate over the arrays:

for( String[] myarr : arrays){
 //Do something with myarr
}

Solution 2: I don't think this is a good idea but if you are sure the file always is going to contain 4 lines you can do this

String arr1[];
String arr2[];
String arr3[];
String arr4[];
try {
 BufferedReader in = new BufferedReader(new FileReader("infilename"));
 String str;
 str = in.readLine();
 arr1[] = str.split(" ");
 str = in.readLine();
 arr2[] = str.split(" ");
 str = in.readLine();
 arr3[] = str.split(" ");
 str = in.readLine();
 arr4[] = str.split(" ");
 in.close();
 } catch (IOException e) {
 }
answered Mar 28, 2010 at 18:26

4 Comments

Thanks, but what I mean is that the every line will be saved in different array. e.g. I will have 4 different arrays with the sizes of 10 each. Not in the same array.
e.g. there are 4 lines in the txt file will create 4 arrays. each array will have the size if 10. and each elements on the array can be called as e.g. array1.get(i)
I have updated the answer to iterate over the 4 arrays. Are you always going to have 4 arrays?
THANK YOU.. yes the text file will always contained 4 lines..:-)
1

look at String[] split

answered Mar 28, 2010 at 18:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.