将文本文件中的输入保存到数组中

4
如何将文本文件内容保存到不同的数组中?
我的文本文件内容是这样的:
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

如何将每一行保存到不同的数组中? 例如:
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
2个回答

3

解决方案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) {
    }

在最后,数组将包含每个数组。在你的例子中,arrays.length()==4
遍历这些数组的方法如下:
for( String[] myarr : arrays){
   //Do something with myarr
}

解决方案2:我不认为这是一个好主意,但如果你确信文件总是会包含4行,你可以这样做。
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) {
    }

谢谢,但我的意思是每一行将保存在不同的数组中。例如,我将有4个不同的数组,每个数组大小为10。不是在同一个数组中。 - Jessy
在文本文件中有4行,将创建4个数组。每个数组的大小为10。可以通过array1.get(i)来调用数组中的每个元素。 - Jessy
我已经更新了答案,以便遍历这4个数组。 你总是会有4个数组吗? - Enrique
谢谢。是的,文本文件始终包含4行.. :-) - Jessy

1

看一下 String[] split


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接