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();
}

tags: zlashdot Java Java

Posted by NI-Lab. (@nilab)