根据标题分割文本文件

问题描述 投票:0回答:1

我有一个文本文件,我需要只读取数字数字,然后用这些数字填充一个数组,我知道如何从文件中读取,下面是我的代码,但我不知道如何只读取这些数字。

LOCATION
6     7
POINT
8     9
JOBS
1     4
4     9
11    8
9     6
5     2

我知道如何从文件中读取,下面是我的代码,但我就是不知道如何只读取这些数字。我不知道如何正确使用分割方法。

BufferedReader objReader = null;
   try {
      String strCurrentLine;

      objReader = new BufferedReader(new FileReader("D:\\Jobs.txt"));

   while ((strCurrentLine = objReader.readLine()) != null) {
    System.out.println(strCurrentLine); //test
   }

  } catch (IOException e) {

   e.printStackTrace();

  } 
java text
1个回答
1
投票

首先,你将不得不拆分,然后测试是否是一个整数。

while ((strCurrentLine = objReader.readLine()) != null) {
    String words [] = strCurrentLine.split ("\\s+");
    for (String word : words) {
        try {
            Integer.valueOf (word);
            System.out.println(word); 
        } catch NumberFormatException e { // do nothing}
    }
}

1
投票

当涉及到任何涉及解释格式化数据时,我总是喜欢使用regex。

String line;
StringBuilder builder = new StringBuilder();
while ((line = objReader.readLine()) != null) {
    builder.append("\n" + line);
}

objReader.close();

List<Integer> numbers = new ArrayList<Integer>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(builder.toString());
while (m.find()) {
    numbers.add(Integer.parseInt(m.group()));
}

numbers.stream().forEach(System.out::println);

如果你想让数字按行分组,可以试试这个。

String line;
List<List<Integer>> numbers = new ArrayList<List<Integer>>();
while ((line = objReader.readLine()) != null) {
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(line);

    List<Integer> nums = new ArrayList<Integer>();
    while (m.find()) {
        nums.add(Integer.parseInt(m.group()));
    }

    numbers.add(nums);
}

objReader.close();

numbers.stream().flatMap(List::stream).forEach(System.out::println);

输出:

6
7
8
9
1
4
4
9
11
8
9
6
5
2

虽然我不得不承认,可怕的袋熊的解决方案更短,更干净。

© www.soinside.com 2019 - 2024. All rights reserved.