Следует ли мне закрыть FileChannel?

Сегодня я столкнулся с проблемой с одним из наших служебных классов. Это помощник для файлов и содержит некоторые процедуры статического копирования файлов. Ниже приведены соответствующие методы, извлеченные вместе с методом тестирования.

Проблема в том, что иногда вызов setLastModified завершается неудачно, возвращая false.

На моем ПК (Windows 7, последняя версия Java) я иногда получаю сообщение «setLastModified failed» (примерно 25 раз из 1000).

Я решил решить эту проблему прямо сейчас, удалив вызовы 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 также закрывает поток .

12
задан OldCurmudgeon 27 July 2012 в 21:25
поделиться