« 関数型プログラミング言語 Haskell とは | メイン | Javaで最短一致正規表現のサンプル »
2007年04月21日
Java nio でテキストファイルの読み書き
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
// テキストファイルの読み書き
public class TextFile {
public static void main(String[] args) throws Exception {
String s = readTextFile("a.txt");
System.out.println(s);
writeTextFile("b.txt", s);
}
private static String readTextFile(String path) throws Exception {
RandomAccessFile raf = new RandomAccessFile(path, "r");
FileChannel fc = raf.getChannel();
ByteBuffer bb = ByteBuffer.allocate((int) fc.size());
fc.read(bb);
raf.close();
return new String(bb.array(), "UTF-8");
}
private static void writeTextFile(String path, String content) throws Exception {
byte[] b = content.getBytes("UTF-8");
ByteBuffer bb = ByteBuffer.wrap(b);
RandomAccessFile raf = new RandomAccessFile(path, "rw");
FileChannel fc = raf.getChannel();
fc.write(bb);
raf.close();
}
}
追記: 2007-05-19
上の writeTextFile メソッドだとすでにファイルが存在している場合に追記になってしまうので、やっぱり java.io パッケージを使って出力したほうがラクかも。
private static void writeTextFile(String path, String content) throws Exception {
BufferedWriter writer =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(path), "UTF-8"));
writer.write(content);
writer.flush();
writer.close();
}
投稿者 NI-Lab. : 2007年04月21日 11:18

コメントはこちらの Ido-Batarian BBS へどうぞ。