【问题标题】:How to print first word from a file separeted by a tab line?如何打印由制表符分隔的文件中的第一个单词?
【发布时间】:2021-02-27 18:51:22
【问题描述】:

我正在尝试读取文件并仅打印每行的第一个数字。我曾尝试使用拆分,但它永远不会返回正确的结果,它只是打印整个内容,如下表所示。任何帮助将不胜感激

**thats my file** 

 40    3  Trottmann
 43    3  Brubpacher
252    3  Stalder
255    3  Leuch
258    3  Zeller
261    3  Reolon
264    3  Ehrismann
267    3  Wipf
270    3  Widmer 

**expected output** 
 40
 43
258
261
264
267
270

输出

258
261
264
267
270

公开课词{

            public static void main(String[] args) {
                
                // Create file
                File file = new File("/Users/lobsang/documents/start.txt");
    
                try {
                    // Create a buffered reader
                    // to read each line from a file.
                    BufferedReader in = new BufferedReader(new FileReader(file));
                    String s;
    
                    // Read each line from the file and echo it to the screen.
                    s = in.readLine();
                    while (s != null) {
                        
                          
                        
                        System.out.println(s.split("\s")[0]);
                    
                        
                        s = in.readLine();
                    }
                    
                    // Close the buffered reader
                    in.close();
    
                } catch (FileNotFoundException e1) {
                    // If this file does not exist
                    System.err.println("File not found: " + file);
    
                } catch (IOException e2) {
                    // Catch any other IO exceptions.
                    e2.printStackTrace();
                }
            }
    
        }

【问题讨论】:

  • split 方法中的正则表达式在技术上是正确的,但您需要在 java 中转义反斜杠。所以固定线路是:System.out.println(s.split("\\s")[0]);
  • 谢谢它确实有效.. 你能再看看我的输出吗.. 做了一些改变.. 对于所有数字小于三的数字,它输出只是空的。可能是因为初始空间而不是数字..我如何更新我的表达式,以便它显示所有数字,包括 1 和 2 位数字 r
  • 我在下面添加了一个答案。

标签: java flatfilereader


【解决方案1】:

要匹配正则表达式中具有特殊含义的字符,您需要使用带有反斜杠 (\) 的转义序列前缀。空格的转义序列为\s,因此您需要将"\s" 替换为"\\s"

【讨论】:

    【解决方案2】:

    您需要双反斜杠才能读取反斜杠,所以这样做:

    System.out.println(s.split("\\s")[0]);

    代替:

    System.out.println(s.split("\s")[0]);

    【讨论】:

      【解决方案3】:

      正如我已经在 cmets 中回答的那样,您需要在 java 中转义反斜杠。 此外,您可以在拆分之前trim() 字符串,这会删除前导和尾随空格。这意味着,它也适用于两位数或一位数。所以你应该使用的是:

      System.out.println(s.trim().split("\\s")[0]);
      

      【讨论】:

      猜你喜欢
      • 2013-10-20
      • 2015-02-26
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      相关资源
      最近更新 更多