java - 我应该关闭 FileChannel 吗?

标签 java filechannel

我今天遇到了一个与我们的实用程序类有关的问题。它是文件的助手,包含一些静态文件复制例程。以下是提取的相关方法和测试方法。

问题是有时 setLastModified 调用会失败,返回 false。

在我的 PC(Windows 7,最新的 Java)上,我有时会收到“setLastModified failed”消息(1000 次中大约有 25 次)。

我现在已经通过删除 FileChannel.close 调用解决了这个问题,但我更愿意理解为什么会发生这种情况,即使这是正确的解决方案。

有没有人遇到同样的问题?

private void testCopy() throws FileNotFoundException, IOException {
  File src = new File("C:\\Public\\Test-Src.txt");
  File dst = new File("C:\\Public\\Test-Dst.txt");

  for (int i = 0; i < 1000; i++) {
    copyFile(src, dst);
  }
}

public static void copyFile(final File from, final File to) throws FileNotFoundException, IOException {
  final String tmpName = to.getAbsolutePath() + ".tmp";
  // Copy to a .tmp file.
  final File tmp = new File(tmpName);
  // Do the transfer.
  transfer(from, tmp);
  // Preserve time.
  if (!tmp.setLastModified(from.lastModified())) {
    System.err.println("setLastModified failed!");
  }
  // In case there's one there already.
  to.delete();
  // Rename it in.
  tmp.renameTo(to);
}

public static void transfer(final File from, final File to) throws IOException {
  FileInputStream in = null;
  FileOutputStream out = null;
  try {
    in = new FileInputStream(from);
    out = new FileOutputStream(to);
    transfer(in, out);
  } finally {
    if (null != in) {
      in.close();
    }
    if (null != out) {
      out.close();
    }
  }
}

public static void transfer(final FileInputStream from, final FileOutputStream to) throws IOException {
  FileChannel srcChannel = null;
  FileChannel dstChannel = null;
  //try {
    srcChannel = from.getChannel();
    dstChannel = to.getChannel();
    srcChannel.transferTo(0, srcChannel.size(), dstChannel);
  //} finally {
  //  if (null != dstChannel) {
  //    dstChannel.close();
  //  }
  //  if (null != srcChannel) {
  //    srcChannel.close();
  //  }
  }
}

编辑:我更改了代码以仅关闭 Streams 而不是 FileChannel 因为研究建议关闭 FileChannel 也会关闭 Stream

最佳答案

在对拥有 Java 库源的各种站点进行一些研究之后,它看起来非常像 FileChannel.close 最终调用 FileInputStream.closeFileOutputStream.close 其父对象。

这向我建议您应该关闭 FileChannel 或 Stream,但不能同时关闭这两者

鉴于此,我正在更改我的原始帖子以反射(reflect)一种正确的方法,即关闭 Stream 而不是 Channel

关于java - 我应该关闭 FileChannel 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8066130/

相关文章:

java - 如何在 jsf 1.2 中使用 DynamicJasper

java - 将数据写入文件会删除之前的所有内容(放置 00)并更改文件大小

java - 使用文件 channel 随机访问文件?

java - 多个线程可以看到 Java 中直接映射的 ByteBuffer 上的写入吗?

Java 录音和混音器设置

java - 不兼容的类型 : inferred type does not conform to upper bound(s)

java - 如何为导航菜单选择提供功能?

java - 缓冲字节数组(来自 DatagramPacket)

java - 处理大图像

Java 可能的 FileChannel.map 错误