您要克服的基本问题是原始java.io
API 根本不灵活(它们都引用具体类)。例如,您可以将不同功能放入其中的唯一方法java.io.File
是扩展基类。
在设计类之后扩展类可能是糟糕的设计(只需查看Properties
类)——这就是为什么您可能找不到这样做的库的原因。
没有什么能阻止您java.io.File
自己扩展类,并将所有方法代理到,例如,FileObject
Commons VFS API 的一个。
编辑:但是,在这种方法下,有些事情可能会失败 - 例如,使用File
带有 parent 的构造函数File
。
编辑2:好吧,我将从这样的事情开始:
public class VirtualFile extends java.io.File {
public static VirtualFile fromFile(File file) {
if (file instanceof VirtualFile) {
return (VirtualFile) file;
} else {
FileSystemManager fsm = new DefaultFileSystemManager();
return fsm.toFileObject(file);
}
}
private final org.apache.commons.vfs.FileObject mProxyFileObject;
public VirtualFile(FileObject proxy) {
super("/tmp/xxxx"); // That part needs some work to be cross-platform.
// However, such a construction will completely
// destroy the expectations that other classes
// have about what a File is.
mProxyFileObject = proxy;
}
public VirtualFile(VirtualFile parent, String child) {
this(parent.mProxyFileObject.resolveFile(child));
}
public VirtualFile(File parent, String child) {
this(fromFile(parent), child);
}
@Override
public boolean canExecute() {
throw new UnsupportedOperationException();
}
@Override
public boolean canRead() {
try {
return mProxyFileObject.isReadable();
} catch (FileSystemException fse) {
// FileSystemException is not a Runtime Exception :(
throw new RuntimeException(fse);
}
}
// Override ALL public methods to throw Exceptions;
// implement or mock only the methods that you need.
}
至于为什么File(File, String)
构造函数不能使用该设置:该构造函数不希望实现File
破坏类的契约——我们在调用super("/tmp/xxxx")
. (而且我们不能避免打破类的契约,因为我们想要使用的虚拟文件没有一个普通的File
等价物)
所以,你来了——这需要做一些不平凡的工作,而且图书馆很可能无法按预期工作。