J2SE の API を目的別に調べることができる辞典

ホーム > Java(SE) API 逆引き辞典 > ファイル > ファイルから文字列で1行ずつ読み込む

Java(SE) API 逆引き辞典

:: reverse dictionary ::

ファイル

※ソースファイルについて

◎各マークの意味
Pbpubic Prprotected Sstatic


ファイルから文字列で1行ずつ読み込む

ファイルから文字列で1行ずつ読み込むには、BufferedReader クラスの readLine メソッドを使います。

≪宣言≫

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
FileInputStream stream = null;
InputStreamReader isr = null;
BufferedReader br = null;

String[] strs = new String[10];  // 読み込む文字列

File file = new File("sample.txt");
try {
  stream = new FileInputStream(file);
  isr = new InputStreamReader(stream);
  br = new BufferedReader(isr);

  int count = 0;
  String read;
  while ((read = br.readLine()) != null) {  // 読み込み
    strs[count] = read;
    count++;
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    if (br != null) {
      br.close();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

ソースファイル

sample.txt の内容が

1行目
2行目
3行目

となっている場合、strs[0]"1行目"strs[1]"2行目"strs[2]"3行目" になります。

▼ メソッド

java.io.BufferedReader
Pb String readLine() throws IOException

BufferedReader オブジェクトの入力ストリームから文字列で1行を読み込みます。

●戻り値

・読み込む行がある … 読み込んだ文字列
・読み込む行がない(入力ストリームの終わり) … null

●例外
IOException
入出力エラーが発生した場合

注目キーワード ベスト5

  1. セキュリティ
  2. ホスティング
  3. レンタルサーバ
  4. ファイル復旧
  5. ハードディスク修復

ファイル - file -


ホーム > Java(SE) API 逆引き辞典 > ファイル > ファイルから文字列で1行ずつ読み込む

Copyright (C) 2005-2007 Noto Watabe. All rights reserved.
e-mail:wmh@always-pg.com