我想通过使用 notExists(Path path, LinkOption... options) 检查目录是否存在,并且我对 LinkOption.NOFOLLOW_LINKS 感到困惑,尽管在我用谷歌搜索之后我仍然不太明白何时使用它。这是我的代码:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.*;
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) throws IOException
{
Path source = Paths.get("Path/Source");
Path destination = Paths.get("Path/Destination");
ArrayList<String> files = new ArrayList<String>();
int retry = 3;
// get files inside source directory
files = getFiles(source);
// move all files inside source directory
for (int j=0; j < files.size(); j++){
moveFile(source,destination,files.get(j),retry);
}
}
// move file to destination directory
public static void moveFile(Path source, Path destination, String file, int retry){
while (retry>0){
try {
// if destination path not exist, create directory
if (Files.notExists(destination, LinkOption.NOFOLLOW_LINKS)) {
// make directory
Files.createDirectories(destination);
}
// move file to destination path
Path temp = Files.move(source.resolve(file),destination.resolve(file));
// if successfully, break
if(temp != null){
break;
}
// else, retry
else {
--retry;
}
} catch (Exception e){
// retry if error occurs
--retry;
}
}
}
// get all file names in source directory
public static ArrayList<String> getFiles(Path source){
ArrayList<String> filenames = new ArrayList<String>();
File folder = new File(source.toString());
File[] listOfFiles = folder.listFiles(); // get all files inside the source directory
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
filenames.add(listOfFiles[i].getName()); // add file's name into arraylist
}
}
return filenames;
}
}
使用 LinkOption.NOFOLLOW_LINKS 和不使用它的结果是一样的(文件被传输到目的地)。所以,我猜我的情况,我可以忽略链接选项吗?另外,在什么情况下我需要那个?谢谢!