【问题标题】:save input from text file to array将输入从文本文件保存到数组
【发布时间】:2011-02-01 19:08:28
【问题描述】:

如何将文本文件内容保存到不同的数组中?

我的文本文件内容是这样的;

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

【问题讨论】:

    标签: java file text arrays


    【解决方案1】:

    解决方案 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。不在同一个数组中。
    • 例如txt 文件中有 4 行将创建 4 个数组。如果每个数组的大小为 10。并且数组上的每个元素都可以称为例如array1.get(i)
    • 我已更新答案以迭代 4 个数组。你总是有 4 个数组吗?
    • 谢谢..是的,文本文件将始终包含 4 行..:-)
    【解决方案2】:

    看String[]拆分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-24
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多