需要如何使标志值为真

时间:2016-12-13 15:01:17

标签: java

我需要调用这个交换文件函数并执行...但是标志值总是保持为假..我需要以某种方式删除文件并使标志值为真..

    void swap_file()
{
   File f = new File("E:\\dream_store\\Employee.txt");
   File t = new File("E:\\dream_store\\temp.txt");
   boolean flag = f.delete();
   t.renameTo(f);
   if (flag)
   {
       JOptionPane.showMessageDialog(null, "File swaped");
   }
   else JOptionPane.showMessageDialog(null, "File not swaped");
}

2 个答案:

答案 0 :(得分:0)

当且仅当文件被成功删除时,

File.delete()才会返回true。因此,如果您的返回值为false,则由于某种原因,删除操作尚未发生。

在删除之前(即使是暂时的)可能需要添加一些额外的代码来验证您的路径是否正确。尝试(至少):

 if(! f.exists()) {
      throw new FileNotFoundException("File does not exist: " + f);
 }

查看File的文档,了解您可以测试的其他方法。

答案 1 :(得分:0)

您应该使用Files中的java.nio.file,然后您可以使用:

Path sourceFile = Paths.get("path to the source file")
Path targetFile = Paths.get("path to the target file")
Files.move(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);

请注意,此处的标记没有任何意义,因为文件将始终被移动,除非它不存在。如果它不存在,那么您可以通过调用Files.exists(...)来检查。

如果要在文件替换文件的情况下打印消息,则可以将其包含在try ... catch (IOException e)中。

相关问题