前回はnio2を使ってファイル分割したけど、Fileクラスを使う場合に比べて、あんまり素敵ではありませんでした。
Java7のnio2を使ってファイルを分割する - きしだのはてな
そしたら、skrbさんにnioのFileChannelだったらもっといいかもと助言もらったので、ちょっと書いてみました。
途中経過が表示できなくなったけど、短くなりました。途中経過を表示するようにすると、同じくらいの長さになっちゃう気がします。
import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileChannelSplit { private static final String FROM = "C:\\分割するファイル"; private static final String TO = "C:\\分割先"; private static final long LIMIT = 1024 * 1024; public static void main(String[] args) throws IOException{ Path p = Paths.get(FROM); try(FileChannel readChannel = FileChannel.open( p, StandardOpenOption.READ)){ long size = readChannel.size(); String filename = p.getFileName().toString(); int idx = 1; for(int total = 0; total < size; total += LIMIT){ Path to = Paths.get(TO, filename + "." + idx); System.out.println(to.toString()); try(FileChannel writeChannel = FileChannel.open( to, StandardOpenOption.CREATE, StandardOpenOption.WRITE)){ MappedByteBuffer readBuffer = readChannel.map( FileChannel.MapMode.READ_ONLY, total, Math.min(size - total, LIMIT)); writeChannel.write(readBuffer); } ++idx; } } } }