繁体   English   中英

备用读取文件方法

[英]Alternative read file method

我无法从文件中存储值。

3
10 2
100 35
5 4
17 20 3 5
6 10
6 9 12 15 18 21 24 27 30 33

我希望将第一行存储为整数,将其他行与多个值存储为单独的int数组。

    BufferedReader br = null;
    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("candy.dat"));
        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

还有其他方法吗? 谢谢

编辑:基本上第一个整数(在此示例中为3)将表示要遵循的测试用例数。 每个测试用例后面都会有两行。 因此,第一个测试用例是[10,2] [100,35]。

EDIT2:如果有人在想,我设法解决了我的问题。 这是我的代码

    Scanner sc = new Scanner(new File("candy.dat"));
    String testCase = sc.nextLine();
    String[] numOfCandy = new String[0];
    String[] NK = new String[0];

    for (int i = 0; i < Integer.parseInt(testCase); i++) {
        System.out.println("test case " + (i+1));
        NK = sc.nextLine().split(" ");
        numOfCandy = sc.nextLine().split(" ");

        //System.out.println(NK[0] + " " + NK[1]);
        //System.out.println(numOfCandy[0] + " " + numOfCandy[1]);

        find(NK[0], NK[1], numOfCandy); //method to solve problem
    }

我首先存储了测试用例的值3,以告知for循环运行多少次。

我实例化了2个String数组供以后使用。

在for循环中,我读取下一行并将其拆分以存储到字符串数组NK中,然后将其后的一行存储到numOfCandy中。

从那里,我能够成功地从阵列中检索数据来解决我的问题。

答案,现在,没有时间,没有大脑...挺酷的态度:

public static void main() throws Exception {
    final Scanner scanner = new Scanner(new File(file_str));
    while (scanner.hasNextLine()) {
        if (scanner.hasNextInt()) {
            final int nb = scanner.nextInt();
            System.err.println(nb);
            final String[] str = scanner.findInLine(".*").split(" ");
            System.err.println("-----" + str);
        }

    }
    System.err.println("END");
    scanner.close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM