Java-Move nextLine with method

时间:2018-03-29 04:47:37

标签: java file io bufferedreader

我有一个多行文本文件,我需要将每一行分配给不同的数组。 我已经为此创建了一个方法,但它无法正常工作。这就是我的主要方法。

    public static void main(String[] args){
    String[] arr = new String[20];
    fromTextToArray(arr); //after this method call, the console needs to move next Line
    String[] arr2 = new String[20];
    fromTextToArray(arr2);
  }

这就是我的方法。

 public static void fromTextToArray(String[] strArray) throws IOException{
    BufferedReader brTest = new BufferedReader(new FileReader("csalg.txt"));
    String text = brTest.readLine();
    brTest.readLine();
    strArray = text.split(",");
    System.out.println(Arrays.toString(strArray));
    text = brTest.readLine(); // this is where I try to move next line for my second array
}

文件中的数字:

1    5 4 4 7 5 5 5 5 3 3 7 7 4 5 2
2    4 5 4 3 4 5 2 3 4 5 5
4    9 10 13 9 8 12 20 16 12 16 6 9 5 5 19 15 16 16 10
8    3 5 1 3 2 7 2 4 7 6 1

期望的输出:

arr [] = {1,5,4,7,5,5,5,3,3,7,4,5,2}
arr2 [] = {2,4,5,4,3,4,5,2,3,4,5,5}

是否可以移至方法中的下一行?或者以任何不同的方式这样做?

1 个答案:

答案 0 :(得分:1)

您在方法中声明读者,因此每次从文件开头开始。 此外,使用try-with-resource来处理关闭阅读器或编写try-catch-finaly并自行关闭它。

您可以让方法决定字符串数组的长度,无需您这样做。

 public static void main(String[] args) throws IOException {

    try (BufferedReader brTest = new BufferedReader(new FileReader("s.txt"))) {
        String[] arr = fromTextToArray(brTest.readLine());// line 1
        brTest.readLine(); // skip line 2
        String[] arr2 = fromTextToArray(brTest.readLine());// line 3
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr2));
    }
}

public static String[] fromTextToArray(String text) throws IOException {

    String[] arr = text.split(",");
    return arr;
}