LoginSignup
0
1

More than 5 years have passed since last update.

バイトストリームと文字ストリームでテキストファイルコピー

Posted at

やりたいこと

①バイトストリームと文字ストリームを使って、テキストファイルをコピーする。

バイトストリームと文字ストリームって2つあるの紛らわしい……。


バイトストリーム

byte.cs
try{

  // コピー元のファイル
  FileStream fstr_in = new FileStream("From.txt", FileMode.Open);
  // コピー先。
  // FileMode.Create →ファイルが存在しない時は新たに作成し、存在するときは上書きする
  FileStream fstr_out = new FileStream("To.txt", FileMode.Create); 
  // テキストコピー
  int i;
  do {
    i = fstr.ReadByte();         // バイトを読み取り、読み取り位置を 1 バイト進める
    fstr_out.WriteByte((Byte)i); // 現在位置にバイトを書き込む
  } while (i != -1);             // ストリームの末尾に達した場合は「-1」が返る

  fstr.Dispose();
  fstr_out.Dispose();

} catch (Exception e) {
  Debug.WriteLine("!例外発生!" + e.ToString());
}

文字ストリーム

str.cs
try{

  // コピー元のファイル
  StreamReader strRead_in = new StreamReader(new FileStream("From.txt", FileMode.Open));
  // コピー先。
  // FileMode.Create →ファイルが存在しない時は新たに作成し、存在するときは上書きする
  StreamWriter strRead_out = new StreamWriter(new FileStream("To.txt", FileMode.Create));
  // テキストコピー
  int i;
  do {
    i = strRead_in.Read();      // 次の文字を読み込み、1 文字分だけ文字位置を進める
    strRead_out.Write((char)i); // ストリームに文字を書き込む
  } while (i != -1);            // 使用できる文字がない場合は「-1」が返る

  strRead_in.Dispose();
  strRead_out.Dispose();

} catch (Exception e) {
  Debug.WriteLine("!例外発生!" + e.ToString());
}

バイトストリームは1バイト、文字ストリームは2バイト。
日本語とか2バイト文字を扱うときは文字ストリームを使う方が良い。

おまけ

VisualStudio2017を使っていたら、「このファイルは外部で変更され、このエディターでは変更は保存されていません。」ダイアログの「チェックボックスをON」、「すべて無視」を選択してしまい、
確認ダイアログも表示されずテキストの出力もされなくなってしまった……(´・ω・`)
image.png

「ツール>設定のインポートとエクスポート → すべての設定をリセット」
で無理やり元に戻したけど……どこか設定するところがあるのかな。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1