5月15日

24章 ストリームを使いこなす

Writerを使う

WriterSample.java

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class WriterSample {

	public static void main(String[] args) throws IOException {
		String path = "hoge.txt";
		Writer out = new FileWriter(path);
		out.write("foo");
		out.write("bar");
		out.close();
		System.out.println("END");
	}

}

Writerのデコレータを使う

WriterSample2.java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriterSample2 {

	public static void main(String[] args) throws IOException {
		String path = "hoge.txt";
		PrintWriter out = new PrintWriter(
				new BufferedWriter(new FileWriter(path)));
		out.println("foo");
		out.println("baa");
		out.close();
		System.out.println("END");
	}
}

Readerを使う

ReaderSample.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReaderSample {

	public static void main(String[] args) throws IOException {
		String path = "hoge.txt";
		BufferedReader in = new BufferedReader(new FileReader(path));
		String line;
		while ((line = in.readLine()) != null) {
			System.out.println(line);
		}
		in.close();
	}

}

バイナリデータの入出力

OutputStreamを使う

OutputSample.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


public class OutputSample {

	public static void main(String[] args) throws IOException {
		String path = "btest.bin";
		OutputStream out = new FileOutputStream(path);
		byte[] b = new byte[] {0x0a, 0x0b, 0x0c};
		out.write(b);
		out.close();
		System.out.println("END");
	}

}

InputStreamを使う

InputSample.java

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class InputSample {

	public static void main(String[] args) throws IOException {
		String path = "btest.bin";
		InputStream in = new FileInputStream(path);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int len;
		byte[] b = new byte[1024];
		while (true) {
			len = in.read(b);
			if (len < 0) break;
			out.write(b, 0, len);
		}
		in.close();
		byte[] result = out.toByteArray();
		for (int i = 0; i < result.length; i++) {
			System.out.print(Integer.toHexString(result[i]) + " ");
		}
	}

}

ファイルをコピーする

FileCopy.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

	public static void main(String[] args) throws IOException {
		String src = "hoge.txt";
		String dest = "hoge2.txt";
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dest);
		int len;
		byte[] b = new byte[1024];
		while (true) {
			len = in.read(b);
			if (len < 0) break;
			out.write(b, 0, len);
		}
		in.close();
		out.close();
		System.out.println("END");
	}

}

必ずcloseする

CloseSample.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class CloseSample {

	public static void main(String[] args) throws IOException {
		String src = "hoge.txt";
		String dest = "hoge2.txt";
		copy(dest, src);
	}

	public static void copy(String dest, String src) throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dest);
			int len;
			byte[] b = new byte[1024];
			while (true) {
				len = in.read(b);
				if (len < 0) break;
				out.write(b, 0, len);
			}
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {}
			}
		}
	}
}

Java7から自動でcloseしてくれる機能が追加された。
try-with-resources文を使うと自動的にcloseしてくれる。
自動でcloseしてくれるオブジェクトは、AutoClosableインタフェースを実装しているクラス。

CloseSample2.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CloseSample2 {

	public static void main(String[] args) throws IOException {
		String src = "hoge.txt";
		String dest = "hoge2.txt";
		copy(dest, src);
	}

	public static void copy(String dest, String src) throws IOException {
		try (InputStream in = new FileInputStream(src);
			 OutputStream out = new FileOutputStream(dest)) {
			int len;
			byte[] b = new byte[1024];
			while (true) {
				len = in.read(b);
				if (len < 0) break;
				out.write(b, 0, len);
			}
		}
	}

}

Webページのコピー(ファイル以外の例)

DownloadSample.java を try-with-resources構文で書き換えてみる。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class DownloadSample {

	public static void main(String[] args) throws IOException {
		String dest = "dest.html";
		URL url = new URL("http://www.yahoo.co.jp/");
		try (
				InputStream in = url.openStream();
				OutputStream out = new FileOutputStream(dest)
			) {
			int len;
			byte[] b = new byte[1024];
			while (true) {
				len = in.read(b);
				if (len < 0) break;
				out.write(b, 0, len);
			}
		}
	}
}

Fileクラスを使う

FileSample.java

import java.io.File;

public class FileSample {

	public static void main(String[] args) {
		File file = new File("C:/All-in-One-Eclipse4.4/workspace/c24/");
		list(file);
	}

	private static void list(File parent) {
		File[] children = parent.listFiles();
		if (children != null) {
			for (int i = 0; i < children.length; i++) {
				File file = children[i];
				if (file.isDirectory()) {
					list(file);
				} else {
					System.out.println(file.getAbsolutePath());
				}
			}
		}
	}
}

Dirコマンドを作ってみよう

Dir.java

import java.io.File;

public class Dir {

	public static void main(String[] args) {
		File file = new File(args[0]);
		dir(file);
	}

	private static void dir(File parent) {
		File[] children = parent.listFiles();
		if (children != null) {
			for (int i = 0; i < children.length; i++) {
				File file = children[i];
				System.out.println(file.getName());
			}
		}
	}

}
  1. 引数なしの場合、現在のディレクトリの内容を表示する
  2. /OS オプションが指定されたらサイズ順にソートする
  3. /OD オプションが指定されたら日付順にソートする

引数なしの場合、現在のディレクトリの内容を表示する

Dir.java

import java.io.File;

public class Dir {

	public static void main(String[] args) {
		String path;
		if (args.length == 0) {
			path = ".";
		} else {
			path = args[0];
		}
		File file = new File(path);
		dir(file);
	}

	private static void dir(File parent) {
		File[] children = parent.listFiles();
		if (children != null) {
			for (int i = 0; i < children.length; i++) {
				File file = children[i];
				System.out.println(file.getName());
			}
		}
	}
}

オプションの取得と条件分岐

Dir.java

import java.io.File;

public class Dir {

	public static void main(String[] args) {
		String path;
		String option = null;
		if (args.length == 0) {
			path = ".";
		} else {
			path = args[0];
			option = getOption(args);
		}
		File file = new File(path);
		dir(file, option);
	}

	private static String getOption(String[] args) {
		for (String s : args) {
			if (s.startsWith("/")) {
				return s;
			}
		}
		return null;
	}

	private static void dir(File parent, String option) {
		File[] children = parent.listFiles();
		if (children != null) {
			if (option == null) {
				for (int i = 0; i < children.length; i++) {
					File file = children[i];
					System.out.println(file.getName());
				}
			}
			if (option.equals("/OD")) {
				// 日付順
			}
			if (option.equals("/OS")) {
				// サイズ順
			}
		}
	}

}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です