如何读取Java中用空格分隔的字符串和数字?

时间:2014-02-25 21:08:09

标签: java

我一直在研究Java项目,我需要阅读一个看起来像这样的文本文件

1 1'阿尔伯特·爱因斯坦是谁?' '指挥官''物理学家''医生'1 我需要单独取值,例如id = 1,type = 1,question =谁是Albert Einstein,answer1 =指挥官等等。

有没有什么方法可以用空格分隔它们并将字符串保持在整个撇号之间?

2 个答案:

答案 0 :(得分:1)

这很难做到,因为标准字符串拆分不会理解不会在引号内拆分任何内容。

每次找到报价时,您都可以轻松编写自己的手动分割,循环播放,翻转“inQuote”标记。只要找到空格并且未设置标志,就在空格上拆分。

答案 1 :(得分:0)

这应该有效:

try {
    BufferedReader reader = new BufferedReader(new FileReader("the-file-name.txt"));
    ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
    String line = reader.readLine();
    while(line != null) {
        ArrayList<String> values = new ArrayList<String>();
        String curr = "";
        boolean quote = false;
        for(int pos = 0; pos < line.length(); pos++) {
            char c = line.charAt(pos);
            if(c == '\'') {
                quote = !quote;
            }
            else if(c == ' ' && !quote) {
                values.add(curr);
                curr = "";
            }
            else {
                curr += c;
            }
        }
        lines.add(values);
        line = reader.readLine();
    }
    reader.close();
    // Access the first value of the first line as an int
    System.out.println("The first value * 2 is " + (Integer.parseInt(lines.get(0).get(0)) * 2));

    // Access the third value of the first line as a string
    System.out.println("The third value is " + lines.get(0).get(2));
} catch (IOException e) {
    System.out.println("Error reading file: ");
    e.printStackTrace();
} catch (Exception e) {
    System.out.println("Error parsing file: ");
    e.printStackTrace();
}