将String添加到文件名中仍然可以使用它

时间:2016-07-29 13:38:53

标签: java xml file copy

我有一个xml文件,我正在获取其完整路径,并将其传递给我在其名称中添加String的函数。但是,在添加字符串后,我无法使用它(初始完整路径)。怎么做呢,在search(String dirName)中获取完整路径并在lk(String fullpath)中添加字符串后,我仍然可以使用search(String dirName)返回的路径。

public String search( String dirName)throws Exception{
         String fullPath = null;
         File dir = new File(dirName);
            if ( dir.isDirectory() )
            {
                String[] list = dir.list(new FilenameFilter()
                {
                    @Override
                    public boolean accept(File f, String s ) 
                    {
                        return s.endsWith(".xml");
                    }
               });

                if ( list.length > 0 )
                {
                    fullPath = dirName+list[0];
                    lockFile(fullPath);
                    return fullPath;
                }
            }

            return "";

    }

    public void lk( String fullPath) throws Exception {
          File f = new File(fullPath);
          String fileNameWithExt = f.getName();
                try {
                    File newfile =new File(fileNameWithExt+".lock");

                    if(f.renameTo(newfile)){
                        System.out.println("Rename succesful");
                    }else{
                        System.out.println("Rename failed");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
   }

2 个答案:

答案 0 :(得分:1)

试试这个

File originalFile = new File(<file parent path>, "myxmlfile");
File cloneFile = new File(originalFile.getParent(),
         originalFile.getName()+"<anything_i_want_to_add>");
Files.copy(originalFile.toPath(),cloneFile.toPath());
//now your new file exist and you can use it
originalFile.delete();//you delete the original file
...
//after you are done with everything and you want the path back
Files.copy(cloneFile.toPath(),originalFile.toPath());
cloneFile.delete();

答案 1 :(得分:0)

在您的锁定方法中,您正在调用renameTo方法。因此,原始文件名现已消失,并被以 .lock 结尾的新文件名替换。

java.io.File类不是文件指针,而是保存文件名的对象。使用仍然引用旧文件名的文件对象将导致错误。

回答您的问题:如果您想在锁定后使用旧文件名,则必须使用其他方法锁定文件。例如,MS Access通过创建与打开的 .accdb 文件具有相同文件名的锁定文件来锁定其 .accdb 文件。

您可以将此代码用作参考:

public boolean fileIsLocked(File file) {
    File lock = new File(file.getAbsolutePath() + ".lock");
    return lock.exists();
}

public void lockFile(File file) {
    if (!fileIsLocked(file)) {
        File lock = new File(file.getAbsolutePath() + ".lock");
        lock.createNewFile();
        lock.deleteOnExit(); // unlocks file on JVM exit
    }
}

public void unlockFile(File file) {
    if (fileIsLocked(file)) {
        File lock = new File(file.getAbsolutePath() + ".lock");
        lock.delete();
    }
}