从文本文件中仅读取整数并将其存储在数组中

时间:2014-03-13 02:56:40

标签: java

仅从文本文件中读取整数并存储在数组中并将其显示给用户

如何只读取包含整数和字符串的文本文件中的整数..

假设我有一个这样的文本文件..

10 10 100 100 Line
10 20 15 30 Rectangle
100 50 50 Circle
10 10 50 50 Line
0 0 0 xyz

我们应该搜索每个标记,如果我们找到一些有意义的字母Line,Rectangle,Circle 该特定Shape的整数信息应该存储在一个数组中,这是如何实现的。

Scanner s = new Scanner (new File ("a.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
    if (s.hasNextInt()) { // check if next token is an int
        System.out.print(s.nextInt()); // display the found integer
    } else {
        s.next(); // else read the next token
    }
}        

2 个答案:

答案 0 :(得分:1)

这只会读取包含字符串" Line"," Circle"的行上的整数。或"矩形"。

    Scanner s = new Scanner(new File("sample.txt")).useDelimiter("\\n");
    while (s.hasNext()) {
        String line = s.next();
        if(line.matches("^.+(Line|Circle|Rectangle)$")) {
            line = line.replaceAll("(Line|Circle|Rectangle)","");
            String[] tokens = line.split(" ");
            for(String t: tokens) {
                System.out.print(t+" ");
            }
        }
    }

以上打印出: 10 10 100 100 10 20 15 30 100 50 50 10 10 50 50

答案 1 :(得分:0)

一种优雅的方式是使用Antlr 并定义你的词法分析器和解析器规则。

否则:

BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
    String[] parts = string.split(" "); // this splits the line by spaces
    // ... it is trivial what you should do next
    //
}

你可以遍历每一行的标记 使用integer.parseInt(parts [i])解析为Int并捕获String的异常。但这不是很优雅。

您可以使用正则表达式代替匹配。