import java.io.*; public class FileReadWriteExample { public static void main(String[] args) { try { FileInputStream fileInputStream = new FileInputStream("input.txt"); FileOutputStream fileOutputStream = new FileOutputStream("output.txt"); int data; while ((data = fileInputStream.read()) != -1) { fileOutputStream.write(data); } fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } import java.nio.*; import java.nio.channels.*; public class AsyncFileReadWriteExample { public static void main(String[] args) { try { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("input.txt"), StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() { public void completed(Integer result, ByteBuffer attachment) { attachment.flip(); AsynchronousFileChannel outFileChannel = AsynchronousFileChannel.open(Paths.get("output.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE); outFileChannel.write(attachment, 0, attachment, new CompletionHandler<Integer, ByteBuffer>() { public void completed(Integer result, ByteBuffer attachment) { outFileChannel.close(); } public void failed(Throwable exc, ByteBuffer attachment) { exc.printStackTrace(); } }); } public void failed(Throwable exc, ByteBuffer attachment) { exc.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文