簡體   English   中英

讀取文件時如何檢測換行

[英]How to detect new line while reading file

我正在嘗試從正常工作的文件中讀取。 但是,當我到達文件中的位置時,它會跳到下一行(或換行),我試圖找到轉義字符'\\n' ,但從未提及。

import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;

public static void main(String args[]) {
       File file = new File("Directory to file");
       try {
           FileInputStream fis = new FileInputStream(file);
           char current_char;
           while (fis.available() > 0) {
               current_char = (char) fis.read();
               if (current_char == '\n') {
                  System.out.println("We found the newline!!");
               }
            }
       }
       catch (IOException ex) {
         ex.printStackTrace();
       }
}

它讀取的文件包含以下內容:

  This is the first line!
  This is the second line!

不同的平台在換行符上使用不同的字符。 您最好檢查一下字符的類型,而不要與任何文字進行比較:

if (Character.getType(current_char) == Character.LINE_SEPARATOR) {   
   System.out.println("We found the newline!!");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM