简体   繁体   English

Java:检查符号链接文件是否存在

[英]Java: check symbolic link file existence

We talk about java 1.6 here. 我们在这里谈论java 1.6。 Since symoblic link is not yet supported, how can examine the existence of them. 由于尚未支持symoblic链接,如何检查它们的存在。

1: tell wheather the link file itself exists (return true even if the link is broken) 1:告诉链接文件本身是否存在(即使链接断开也返回true)

2: follow the link and tell wheather underlying file exists. 2:按照链接告诉wheather底层文件存在。

Is there really no way to realize this except JNI? 除了JNI,真的没有办法实现这个吗?

It is slow but you could compare getAbsolutePath() and getCanonicalPath() of a File. 它很慢但您可以比较文件的getAbsolutePath()和getCanonicalPath()。 So use only outside a performance critical code path. 因此,只能在性能关键代码路径之外使用。

The following should give you a start: 以下应该给你一个开始:

 
 
 
 
  
  
  if (file.exists() && !file.isDirectory() && !file.isFile()) { // it is a symbolic link (or a named pipe/socket, or maybe some other things) } if (file.exists()) { try { file.getCanonicalFile(); } catch (FileNotFoundException ex) { // it is a broken symbolic link } }
 
 
  

EDIT : The above don't work as I thought because file.isDirectory() and file.isFile() resolve a symbolic link. 编辑 :以上不能正常工作因为file.isDirectory()和file.isFile()解析符号链接。 (We live and learn!) (我们生活和学习!)

If you want an accurate determination, you will need to use JNI to make the relevant native OS-specific library calls. 如果要进行准确的确定,则需要使用JNI进行相关的本机OS特定库调用。

hmm..not yet supported..will it ever be supported is the question that comes to my mind looking at this question...symbolic links are platform specific and Java is supposed to b platform independent. 嗯......还不支持..它是否会受到支持是我脑子里想到这个问题的问题......符号链接是特定于平台的,Java应该是独立于平台的。 i doubt if anything of the sort is possible with java as such..you may have to resort to native code for this portion and use JNI to bridge it with the rest of your program in java. 我怀疑这种类型是否有可能与java一样......你可能不得不求助于这部分的本机代码并使用JNI将它与java中的其余程序桥接。

#2 is easy: just use File.isFile etc., which will traverse the link. #2很简单:只需使用File.isFile等,它将遍历链接。 The hard part is #1. 困难的部分是#1。

So if you cannot use java.nio.file , and want to avoid JNI etc., the only thing I found which works: 所以如果你不能使用java.nio.file ,并且想要避免使用JNI等,我发现它唯一有用的东西:

static boolean exists(File link) {
    File[] kids = link.getParentFile().listFiles();
    return kids != null && Arrays.asList(kids).contains(link);
}

Not terribly efficient but straightforward. 不是非常有效但直截了当。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM