文本文件追加文字
//不加true就是覆盖try (FileOutputStream fos = new FileOutputStream("data.txt", true)) { FileChannel channel = fos.getChannel(); ByteBuffer src = StandardCharsets.UTF_8.encode("你好你好你好你好你好"); // 字节缓冲的容量和limit会随着数据长度变化,不是固定不变的 System.out.println("初始化容量和limit:" + src.capacity() + "," + src.limit()); int length = 0; while ((length = channel.write(src)) != 0) { /* * 注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读 */ System.out.println("写入长度:" + length); }} catch (IOException e) { e.printStackTrace();}
文件复制
//源文件路径String from = "data.txt";//目标文件路径String to = "to.txt";try ( FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel()) { //最多2G //fromChannel.transferTo(0,fromChannel.size(),toChannel); //超过2G的文件复制写法 long size = fromChannel.size(); // left 变量代表还剩余多少字节 long left = size; while (left > 0) { left -= fromChannel.transferTo((size - left), left, toChannel); }} catch (IOException e) { e.printStackTrace();}