【问题标题】:Java - Only read first line of a fileJava - 只读取文件的第一行
【发布时间】:2014-07-10 03:00:46
【问题描述】:

我只想读取文本文件的第一行并将第一行放入字符串数组中。

这是我所拥有的,但它正在读取整个文件。

myTextFile 中的前文本:

Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10





String line= System.getProperty("line.separator");
String strArray[] = new String[5];


String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
    text = brTest .readLine();
        while (text != line) {
            System.out.println("text = " + text );
             strArray= text.split(",");
         }

【问题讨论】:

标签: java


【解决方案1】:

使用BufferedReader.readLine() 获取第一行。

BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
    text = brTest .readLine();
   System.out.println("Firstline is : " + text);

【讨论】:

  • 并添加 brTest.close() 或更好地使用 Java 8 的 try (BufferedReader...) { } 构造。
  • @Anthony, try (..) 是 Java 7 语法:)
【解决方案2】:

使用 Java 8 和 java.nio,您还可以执行以下操作:

String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
    .map(s -> s.split(","))
    .findFirst()
    .get();

如果TAsks 的假设是正确的,您可以通过额外的方式实现这一点

.filter(s -> !s.equals(""))

【讨论】:

  • 小心:Files.lines 不会自动关闭文件。
  • 它真的会将所有内容加载到内存吗?
【解决方案3】:

如果我理解你,那么

String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));

【讨论】:

    【解决方案4】:

    此外,除了此处介绍的所有其他解决方案之外,您还可以使用 guava 实用程序类 (Files),如下所示:

    import com.google.common.io.Files;
    //...
    
    String firstLine = Files.asCharSource(myTextFile).readFirstLine();
    

    【讨论】:

    • 你有链接到哪里可以找到 guave 实用程序以及如何导入它?
    • 添加到答案中。
    【解决方案5】:

    我认为只有当它不为空时才尝试获取一行。

    你可以使用

     while ((text=brTest .readLine())!=null){
        if(!text.equals("")){//Ommit Empty lines
             System.out.println("text = " + text );
             strArray= text.split(",");
             System.out.println(Arrays.toString(strArray));
             break;
        }
     }
    

    【讨论】:

      【解决方案6】:

      使用这个

      BuffereedReader reader = new BufferedReader(new FileReader(textFile));
      StringBuilder builder = new StringBuilder();
      
      StringBuilder sb = new StringBuilder();
      String line = br.readLine();
      
              while (line != null) {
                  sb.append(line);
               break;
              }
      if(sb.toString.trim().length!=0)
      System.out.println("first line"+sb.toString);
      

      【讨论】:

        【解决方案7】:

        我希望这会对某人有所帮助

        阅读第一行:

        public static String getFirstLine() throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); 
        
            String line = br.readLine(); 
            br.close();
            return line;
        }
        

        阅读全文:

        public static String getText() throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); 
            StringBuilder sb = new StringBuilder(); 
            String line = br.readLine(); 
        
            while (line != null) { 
                sb.append(line).append("\n"); 
                line = br.readLine(); 
            } 
            String fileAsString = sb.toString();
            br.close();
            return fileAsString;
        }
        

        【讨论】:

          【解决方案8】:

          你需要改变你的循环条件

            String[] nextLine;   
            while((nextLine = brTest.readLine()) != null) {
                ...
            }
          

          ReadLine 从开始读取每一行直到出现 \r 和或 \n 也可以使用tokenizer分割字符串

          String[] test = "this is a test".split("\\s");
          

          此外,如果文件是 CSV 类型,请在问题中提及。

          【讨论】:

          • @Unihedron 我改了语法
          • 这是读取文件的正确惯用方法,尤其是在过滤到StringBuilder 时。不幸的是,它似乎没有回答这个问题。
          • @Unihedron 有什么问题吗?它会逐行读取所有行,提问者可以在读取第一行后中断循环。
          • 其实,empty lines are returned "" through .readLine()。只有当阅读器到达流的末尾时,.readLine() != null 才会返回 false。也许你想要!= null && ! .equals("")
          • readline 到达 \n 或 \r 时立即停止读取该行,一旦到达那些将读取到的内容放入 nextLine 的行,则您可以使用包含一行的 nextLine 字符串文件。
          猜你喜欢
          • 1970-01-01
          • 2010-12-26
          • 1970-01-01
          • 2011-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多