2013-05-23 15 views
5

1行にタブで区切られたテキストファイルを読み込もうとしています。行は、キャリッジリターン( "\ r \ n")で区切られ、タブで区切られたテキストフィールド内では行送り(\ "n")が許可されます。Java: " n"を無視して1行ずつファイルを読み込む方法

私はファイル行を1行にしたいので、私のプログラムはスタンドアロンの "\ n"を無視したいと思っています。 残念ながら、BufferedReaderは両方の可能性を使用して行を区切ります。スタンドアロンの "\ n"を無視するために、自分のコードを変更するにはどうすればよいですか?

try 
{ 
    BufferedReader in = new BufferedReader(new FileReader(flatFile)); 
    String line = null; 
    while ((line = in.readLine()) != null) 
    { 
     String cells[] = line.split("\t");       
     System.out.println(cells.length); 
     System.out.println(line); 
    } 
    in.close(); 
} 
catch (IOException e) 
{ 
    e.printStackTrace(); 
} 

答えて

15

java.util.Scannerを使用してください。

Scanner scanner = new Scanner(new File(flatFile)); 
scanner.useDelimiter("\r\n"); 
while (scanner.hasNext()) { 
    String line = scanner.next(); 
    String cells[] = line.split("\t");       
    System.out.println(cells.length); 
    System.out.println(line); 
} 
+0

ありがとうございます。これは完璧です! – Del

+0

メソッドの名前は実際にはuseDelimiterです(編集は少なくとも6文字でなければなりませんので、自分で回答を編集することはできません) –

+0

@Krige - 大変感謝しています。私はそれを修正した。 – rolfl

0

あなたは、単にそれが空行をスキップ作ることができます:

while ((line = in.readLine()) != null) { 
    // Skip lines that are empty or only contain whitespace 
    if (line.trim().isEmpty()) { 
     continue; 
    } 

    String[] cells = line.split("\t"); 
    System.out.println(cells.length); 
    System.out.println(line); 
} 
0

apache commons-ioのFileUtils.readLinesメソッドを使用できます。

ファイルの開閉について気にする必要がないという利点があります。それはあなたのために処理されます。

関連する問題