public class TestFile {
@Test
public void testWriteFile() throws Exception {
FileOutputStream fos = new FileOutputStream("basic.txt");
FileChannel fc = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello nio".getBytes());
buffer.flip();
fc.write(buffer);
fos.close();
}
@Test
public void testReadFile() throws Exception {
File file = new File("basic.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
fc.read(buffer);
System.out.println(new String(buffer.array()));
}
@Test
public void testCopyFile() throws Exception {
File file = new File("basic.txt");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("copyBasic.txt");
FileChannel readChannel = fis.getChannel();
FileChannel writeChannel = fos.getChannel();
readChannel.transferTo(0, readChannel.size(), writeChannel);
fis.close();
fos.close();
}
}