【问题标题】:Alternative read file method替代读取文件方法
【发布时间】:2014-03-25 10:54:09
【问题描述】:

我在存储文件中的值时遇到问题。

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 个字符串数组供以后使用。

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

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

【问题讨论】:

  • 你的问题不是很清楚。您有一定程度的工作代码,但似乎您没有尝试进一步使用该解决方案。你到底坚持哪一点?
  • 如果我站在你的立场上,我会将这些数据存储在一些定义明确的结构中,并以 JSON 字符串的形式保存/检索。 2c.

标签: java arrays file store


【解决方案1】:

回答,现在,没时间,没脑子......态度很酷:`

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2012-04-05
    • 2010-12-24
    相关资源
    最近更新 更多