Java - 文字ストリーム


■ページ目次

Top

■文字ストリーム

Top
■文字ストリームのクラス
Top
■文字ストリームを使ってデータを読み込む
Reader クラス
図 Reader クラス
Top
■文字ストリームを使ってデータを書き込む
Writer クラス
図 Writer クラス
Top
■例題
  1. ファイルをコピーするアプリケーション"FileCopy.java"を作成ください。このとき、ファイルのコピー部分は、FileCopy#copyFile()メソッドを使います。
    1. import java.io.*;
    2. public class FileCopy {
    3. public static void main(String[] args) {
    4. if (copyFile(args[0], args[1])) {
    5. System.err.println("File '" + args[0] + "' copied to '" + args[1] + "'.");
    6. } else {
    7. System.err.println("File '" + args[0] + "' does not copied.");
    8. }
    9. }
    10. static boolean copyFile(String inFileName, String outFileName) {
    11. try {
    12. // 文字ストリームの獲得(ファイルのオープン)
    13. BufferedReader br = new BufferedReader(new FileReader(inFileName));
    14. BufferedWriter bw = new BufferedWriter(new FileWriter(outFileName));
    15. String str;
    16. // データの読み込み(入力)
    17. while ((str = br.readLine()) != null) {
    18. // 読み込んだデータの書き込み(出力)
    19. bw.write(str);
    20. bw.newLine();
    21. }
    22. // ストリームのクローズ(ファイルのクローズ)
    23. bw.flush();
    24. bw.close();
    25. br.close();
    26. } catch (FileNotFoundException e) {
    27. return false;
    28. } catch (IOException e) {
    29. e.printStackTrace();
    30. return false;
    31. }
    32. return true;
    33. }
    34. }

    □ 実行結果

    $ java FileCopy FileCopy.java a.txt
    File 'FileCopy.java' copied to 'a.txt'.
    
Top
■実習
  1. (オプション)
    上記のファイルをコピーするアプリケーション
    "FileCopy.java"につぎのオプションを加えてください。("FileCopy.java")
    1. import java.io.*;
    2. public class FileCopy {
    3. public static void main(String[] args) {
    4. String inf = "", outf = "";
    5. String ie = // コードを記述してください。
    6. String oe = // コードを記述してください。
    7. for (int i = 0; i < args.length; i++) {
    8. if (args[i].equals("-ie")) {
    9. ie = args[++i];
    10. } else if (args[i].equals("-oe")) {
    11. oe = args[++i];
    12. } else {
    13. if (inf.equals("")) {
    14. inf = args[i];
    15. } else {
    16. outf = args[i];
    17. }
    18. }
    19. }
    20. if (copyFile(ie, oe, inf, outf)) {
    21. System.err.println("File '" + inf + "(" + ie
    22. + ")' copied to '" + outf + "(" + oe + ")'.");
    23. } else {
    24. System.err.println("File '" + inf + "' does not copied.");
    25. }
    26. }
    27. static boolean copyFile(String inFileEncoding,
    28. String outFileEncoding,
    29. String inFileName,
    30. String outFileName) {
    31. try {
    32. // 文字ストリームの獲得(ファイルのオープン)
    33. BufferedReader br =
    34. // コードを記述してください。
    35. BufferedWriter bw =
    36. // コードを記述してください。
    37. String str;
    38. // データの読み込み(入力)
    39. while ((str = br.readLine()) != null) {
    40. // 読み込んだデータの書き込み(出力)
    41. bw.write(str);
    42. bw.newLine();
    43. }
    44. // ストリームのクローズ(ファイルのクローズ)
    45. bw.flush();
    46. bw.close();
    47. br.close();
    48. } catch (FileNotFoundException e) {
    49. return false;
    50. } catch (IOException e) {
    51. e.printStackTrace();
    52. return false;
    53. }
    54. return true;
    55. }

    □ 実行結果

    $ java FileCopy FileCopy.java a.txt
    File 'Stream.dat(JISAutoDetect)' copied to 'aaa.dat(MS932)'.
    
    $ java FileCopy -ie MS932 Stream.dat aaa.dat
    File 'Stream.dat(JISAutoDetect)' copied to 'aaa.dat(MS932)'.
    
  2. (オプション)
    さらに、上記のファイルをコピーするアプリケーション"FileCopy.java"につぎのオプションを加えてください。("FileCopy.java")
    1. import java.io.*;
    2. public class FileCopy {
    3. public static void main(String[] args) {
    4. // 前問と同じ。
    5. if (outf.equals("")) {
    6. if (encodeFile(ie, oe, inf)) {
    7. System.err.println("File '" + inf + "(" + ie
    8. + ")' encoded to '" + oe + "'.");
    9. } else {
    10. System.err.println("File '" + inf
    11. + "' does not encorded.");
    12. }
    13. } else {
    14. if (copyFile(ie, oe, inf, outf)) {
    15. // 前問と同じ。
    16. }
    17. }
    18. }
    19. static boolean encodeFile(String inFileEncoding,
    20. String outFileEncoding,
    21. String fileName) {
    22. String tmpFileName = fileName + ".tmp";
    23. // コードを記述してください。
    24. return deleteFile(tmpFileName);
    25. }
    26. static boolean deleteFile(String fileName) {
    27. // コードを記述してください。
    28. }
    29. static boolean copyFile(String inFileEncoding,
    30. String outFileEncoding,
    31. String inFileName,
    32. String outFileName) {
    33. // 前問と同じ。
    34. }
    35. }

    □ 実行結果

    $ java FileCopy -ie EUC_JP aaaa.txt
    File 'aaaa.txt(EUC_JP)' encoded to 'MS932'.
    
  3. (オプション)
    さらに、上記のファイルをコピーするアプリケーション"FileCopy.java"をパッケージ化(パッケージ名maruno)して、どのディレクトリーからでも使えるようにしてください。("FileCopy.java")
  4. $ javac -d . FileCopy.java
    $ jar -cf maruno.jar maruno/*.class
    $ cp maruno.jar $JAVA_HOME/jre/lib/ext/
    

    □ 実行結果

    $ java -cp $JAVA_HOME/jre/lib/ext/maruno.jar maruno.FileCopy -ie EUC_JP aaaa.txt
    File 'aaaa.txt(EUC_JP)' encoded to 'MS932'.
    
Top
■商品管理システム
  1. TestProductにおける商品の追加・更新・削除をファイルからできるようにするアプリケーション"AdminProduct.java"を作成ください。入力ファイルの形式はつぎのとおりです。 また、出力ファイルの形式は以下のとおりです。
    1. // 1601
    2. // package server;
    3. // import product.*;
    4. import java.util.*;
    5. import java.io.*;
    6. // セット商品クラスをファイルによって管理するクラスです。
    7. public class AdminProduct {
    8. // ファイルから商品データを読んで、セット商品クラスに商品を設定します。
    9. public void read(SetProduct sp, String fileName) {
    10. BufferedReader br = null;
    11. try {
    12. br = new BufferedReader(new FileReader(fileName));
    13. String s = null;
    14. while ((s = br.readLine()) != null) {
    15. String[] sa = s.split("\t");
    16. if (sa.length >= 2 && sa[0].toUpperCase().equals("D")) {
    17. sp.remove(sa[1]);
    18. } else if (sa.length >= 4 && sa[0].toUpperCase().equals("A")) {
    19. sp.add(new Product(sa[1], sa[2], sa[3]));
    20. } else if (sa.length >= 4 && sa[0].toUpperCase().equals("U")) {
    21. sp.update(new Product(sa[1], sa[2], sa[3]));
    22. } else {
    23. continue;
    24. }
    25. }
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. } finally {
    29. try {
    30. br.close();
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. }
    36. // ファイルにセット商品データの商品を設定します。
    37. public void write(SetProduct sp, String fileName) {
    38. Map p = (Map)sp.getProducts();
    39. BufferedWriter bw = null;
    40. try {
    41. bw = new BufferedWriter(new FileWriter(fileName));
    42. Product product = null;
    43. Iterator itr = p.values().iterator();
    44. while (itr.hasNext()) {
    45. product = (Product)itr.next();
    46. bw.write(product.getCode() + "\t" + product.getName() + "\t" + product.getPrice());
    47. bw.newLine();
    48. }
    49. } catch (IOException e) {
    50. e.printStackTrace();
    51. } finally {
    52. try {
    53. bw.flush();
    54. bw.close();
    55. } catch (IOException e) {
    56. e.printStackTrace();
    57. }
    58. }
    59. }
    60. }
  2. つぎの"TestProduct.java"を作成し、実行してください。
    1. // 1601
    2. // package application;
    3. // import product.*;
    4. import java.util.*;
    5. // 商品クラスをテストするクラスです。
    6. public class TestProduct {
    7. public static void main(String[] args) {
    8. TreeMap p = new TreeMap();
    9. SetProduct s = new SetProduct("SA01", "パソコン・セット", 10, p);
    10. System.out.println("セット商品のインスタンスを生成しました。 s = " + s);
    11. System.out.println();
    12. AdminProduct ap = new AdminProduct();
    13. ap.read(s, args[0]);
    14. System.out.println("商品のデータを入力しました。 p = " + p);
    15. System.out.println("セット商品のデータを設定しました。 s = " + s);
    16. ap.write(s, args[1]);
    17. System.out.println("セット商品のデータをファイルに書き出しました。 s = " + s);
    18. }
    19. }
    A	A001	パソコン	188000
    A	P001	プリンター	24000
    A	C001	CD-ROM	6500
    A	M001	USBメモリー	9800
    A	H001	ハードディスク	9200
    U	C001	DVD-ROM	9200
    D	M001
    

    □ 実行結果

    $ java -cp classes application.TestProduct products.txt out.txt
    セット商品のインスタンスを生成しました。 s = [SA01, パソコン・セット, 10, 0]
    
    商品のデータを入力しました。 p = {A001=[A001, パソコン, 188000], C001=[C001, DVD
    -ROM, 9200], H001=[H001, ハードディスク, 9200], P001=[P001, プリンター, 24000]}
    セット商品のデータを設定しました。 s = [SA01, パソコン・セット, 10, 207360]
    セット商品のデータをファイルに書き出しました。 s = [SA01, パソコン・セット, 10,
    207360]
    
    A001	パソコン	188000
    C001	DVD-ROM	9200
    H001	ハードディスク	9200
    P001	プリンター	24000
    
Top

■入出力時のエンコーディング指定

Top
■InputStreamReader
Top
■OutputStreamWriter
Top
■例題
Top

inserted by FC2 system