文本文件追加文字

  1. //不加true就是覆盖
  2. try (FileOutputStream fos = new FileOutputStream("data.txt", true)) {
  3. FileChannel channel = fos.getChannel();
  4. ByteBuffer src = StandardCharsets.UTF_8.encode("你好你好你好你好你好");
  5. // 字节缓冲的容量和limit会随着数据长度变化,不是固定不变的
  6. System.out.println("初始化容量和limit:" + src.capacity() + "," + src.limit());
  7. int length = 0;
  8. while ((length = channel.write(src)) != 0) {
  9. /*
  10. * 注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读
  11. */
  12. System.out.println("写入长度:" + length);
  13. }
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }

文件复制

  1. //源文件路径
  2. String from = "data.txt";
  3. //目标文件路径
  4. String to = "to.txt";
  5. try (
  6. FileChannel fromChannel = new FileInputStream(from).getChannel();
  7. FileChannel toChannel = new FileOutputStream(to).getChannel()
  8. ) {
  9. //最多2G
  10. //fromChannel.transferTo(0,fromChannel.size(),toChannel);
  11. //超过2G的文件复制写法
  12. long size = fromChannel.size();
  13. // left 变量代表还剩余多少字节
  14. long left = size;
  15. while (left > 0) {
  16. left -= fromChannel.transferTo((size - left), left, toChannel);
  17. }
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }