【问题标题】:Split a text file based on title根据标题拆分文本文件
【发布时间】:2020-04-24 02:06:49
【问题描述】:

我有一个文本文件,我只需要读取数字,然后用这些填充一个数组。

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

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

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】:

    首先你必须拆分,然后测试是否是整数

    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}
        }
    }
    

    【讨论】:

      【解决方案2】:

      当涉及到解释格式化数据的任何事情时,我总是喜欢使用正则表达式:

      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
      

      虽然我不得不承认,Scary Wombat 的解决方案要短得多且更简洁。

      【讨论】:

      • Scary Wombat 的解决方案更简洁更简洁 - 谢谢,但我也不喜欢捕获异常来控制业务逻辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多