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

ホーム > Java(SE) API 逆引き辞典 > ファイル > ファイルに1文字ずつ書き込む

Java(SE) API 逆引き辞典

:: reverse dictionary ::

ファイル

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

◎各マークの意味
Pbpubic Prprotected Sstatic


ファイルに1文字ずつ書き込む

ファイルに1文字ずつ書き込むには、BufferedReader クラスの write メソッドを使います。

≪宣言≫

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
FileOutputStream stream = null;
OutputStreamWriter osr = null;
BufferedWriter bw = null;

// 書き込む文字
char[] chars = new char[] {'A', 'B', 'C'};

File file = new File("sample.txt");
try {
  stream = new FileOutputStream(file);
  osr = new OutputStreamWriter(stream);
  bw = new BufferedWriter(osr);

  for (int i = 0; i < chars.length; i++) {
    // 書き込み
    bw.write((int)chars[i]);
    bw.newLine();
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    if (bw != null) {
      bw.close();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

ソースファイル

実行すると sample.txt の内容が

A
B
C

になります。


全角文字も1文字ずつ書き込むことができます。

FileOutputStream stream = null;
OutputStreamWriter osr = null;
BufferedWriter bw = null;

// 書き込む文字
char[] chars = new char[] {'A', 'B', 'C'};

File file = new File("sample.txt");
try {
  stream = new FileOutputStream(file);
  osr = new OutputStreamWriter(stream);
  bw = new BufferedWriter(osr);

  for (int i = 0; i < chars.length; i++) {
    // 書き込み
    bw.write((int)chars[i]);
    bw.newLine();
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    if (bw != null) {
      bw.close();
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

ソースファイル

実行すると sample.txt の内容が

A
B
C

になります。

▼ メソッド

java.io.BufferedWriter
Pb void write(int c) throws IOException

文字 cBufferedWriter オブジェクトの出力ストリームに書き込みます。

●引数

c … 書き込む文字

●例外
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