用Java唯一标识文件 [英] Uniquely identify file in Java
问题描述
我在Linux上使用,而我的Java应用程序并非旨在可移植.
Im on Linux and my Java application is not intended to be portable.
我正在寻找一种在Java中唯一标识文件的方法.我可以使用statfs
syscall,因为对(f_fsid, ino)
唯一标识文件(不仅在整个文件系统中),而且在此处指定:
I'm looking for a way to identify a file uniquely in Java. I can make use of statfs
syscall since the pair (f_fsid, ino)
uniquely identifies a file (not only across a file system) as specified here: http://man7.org/linux/man-pages/man2/statfs.2.html
问题是,是否有可能直接从Java中提取fsid
,所以我可以避免编写JNI函数?
The question is if it is possible extract fsid
from Java directly so I can avoid writing JNI function?
inode
可以用NIO
提取,但是fsid呢? inode和fsid来自不同的结构,并由不同的系统调用操作...
inode
can be extracted with NIO
, but how about fsid? inode and fsid comes from different structure and are operated by different syscalls...
推荐答案
此Java示例演示了如何获取文件的UNIX索引节点号.
This java example demonstrates how to get the unix inode number of a file.
import java.nio.file.*;
import java.nio.file.attribute.*;
public class MyFile {
public static void main(String[] args) throws Exception {
BasicFileAttributes attr = null;
Path path = Paths.get("MyFile.java");
attr = Files.readAttributes(path, BasicFileAttributes.class);
Object fileKey = attr.fileKey();
String s = fileKey.toString();
String inode = s.substring(s.indexOf("ino=") + 4, s.indexOf(")"));
System.out.println("Inode: " + inode);
}
}
输出
$ java MyFile
Inode: 664938
$ ls -i MyFile.java
664938 MyFile.java
应计入贷项的贷方: https://www.javacodex.com/More -Examples/1/8
这篇关于用Java唯一标识文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!