import java.nio.*; import java.nio.channels.*; import java.io.*; public class ChannelTest2 { private String[] texts = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "あいうえお"}; public ChannelTest2(String filename) { write(filename); read(filename); } public void write(String filename){ try{ FileOutputStream stream = new FileOutputStream(filename); FileChannel channel = stream.getChannel(); for (int i = 0 ; i < texts.length ; i++) { ByteBuffer buffer = ByteBuffer.wrap(texts[i].getBytes()); channel.write(buffer); } channel.close(); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } public void read(String filename){ try{ FileInputStream stream = new FileInputStream(filename); FileChannel channel = stream.getChannel(); int sizeOfReadingBytes = 0; while (sizeOfReadingBytes < channel.size()){ ByteBuffer buffer = ByteBuffer.allocate(10); buffer.clear(); sizeOfReadingBytes += channel.read(buffer); buffer.clear(); byte[] bytes = new byte[buffer.capacity()]; buffer.get(bytes); System.out.println("Buffer: " + new String(bytes)); } channel.close(); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } public static void main(String[] args){ new ChannelTest2(args[0]); } }