テキストファイルをコピーするプログラムを作成しなさい。 ファイル名は TextCopy.java とする。 コマンドラインから、コピー元ファイル名とコピー先ファイル名を受け取るようにしなさい。
$ java TextCopy コピー元ファイル名 コピー先ファイル名
コピーした行数を表示するようにしなさい。
import java.io.*; class TextCopy { public static void main(String args[]) { BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); } catch (IOException e) { System.err.println("File cannot be opened: " + args[0]); System.exit(1); } PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new FileWriter(args[1]))); } catch (IOException e) { System.err.println("File cannot be opened: " + args[1]); System.exit(1); } try { String str; int i = 0; str = in.readLine(); while (str != null) { i++; out.println(str); str = in.readLine(); } System.out.println(i + " lines."); } catch (IOException e) { System.err.println("An error was occured while reading or writing."); } try { in.close(); out.close(); } catch (IOException e) { System.err.println("An error was occured while closing."); } } }
コピーした単語数を表示するようにしなさい。
import java.io.*; import java.util.StringTokenizer; class TextCopy { public static void main(String args[]) { BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); } catch (IOException e) { System.err.println("File cannot be opened: " + args[0]); System.exit(1); } PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new FileWriter(args[1]))); } catch (IOException e) { System.err.println("File cannot be opened: " + args[1]); System.exit(1); } try { String str; int i = 0; str = in.readLine(); while (str != null) { StringTokenizer tokenizer = new StringTokenizer(str, " \t\n\r\f:;,.!?+-*/=(){}[]'\""); i += tokenizer.countTokens(); out.println(str); str = in.readLine(); } System.out.println(i + " words."); } catch (IOException e) { System.err.println("An error was occured while reading or writing."); } try { in.close(); out.close(); } catch (IOException e) { System.err.println("An error was occured while closing."); } } }
StringTokenizer は区切り文字を指定するとそれで文字列を分割してくれる。 indexOf を使ってもよいが、場合分けは多くなる。
テキストファイルから指定した文字列を探し、その文字列が含まれている行を表示するプログラムを作成しなさい。ファイル名は TinyGrep.java とする。
$ java TinyGrep 探す文字列 探す先のファイル名
import java.io.*; class TinyGrep { public static void main(String args[]) { String expression = args[0]; String filename = args[1]; BufferedReader in = null; try { in = new BufferedReader(new FileReader(filename)); } catch (IOException e) { System.err.println("File cannot be opened: " + filename); System.exit(1); } try { String str; int i = 0; str = in.readLine(); while (str != null) { i++; if(str.indexOf(expression) != -1) System.out.println(filename + ":" + i + ":" + str); str = in.readLine(); } } catch (IOException e) { System.err.println("An error was occured while reading."); } try { in.close(); } catch (IOException e) { System.err.println("An error was occured while closing."); } } }