繁体   English   中英

在Java中,有一种方法可以判断文件驻留在哪台物理计算机上?

[英]In java is there a way to tell on which physical computer a file resides?

我有一个日食RCP产品,该产品由我们公司的多个人员运行。 所有PC都运行某些版本的Windows。 我们可以访问一台共享的PC,不同的人已将其映射到不同的驱动器号。 这意味着可以根据运行程序的PC以多种不同方式引用同一文件。 例如

  • \\ communalPC \\共享\\ foo.txt的
  • Y:\\共享\\ foo.txt的
  • Z:\\共享\\ foo.txt的

我想以编程方式检查公用PC上是否有任意文件。 有没有在Java中执行此操作的可靠方法?

我们下面的当前解决方案有些破绽,由于人们映射到不同的驱动器号,更改驱动器号,不可移植等原因,它并不强大。

private static boolean isOnCommunalPc(File file) {
    if(file.getAbsolutePath().toLowerCase().startsWith("\\\\communalPC")) {
        return true;
    }

    if(file.getAbsolutePath().toLowerCase().startsWith("y:")){
        return true;
    }

    if(file.getAbsolutePath().toLowerCase().startsWith("z:")){
       return true;
    }

    return false;
}

Java无法区分文件在哪台计算机上,因为Windows从JVM提取了该层。 您可以,但是对您的连接要明确。

有没有理由为什么您不能在公用PC上安装ftp或http服务器(甚至是自定义的Java服务器!),而无法通过主机名或ip访问它? 这样,通过静态地址连接的用户在哪里映射了网络驱动器都没有关系。

使用Java访问远程文件非常简单:

URL remoteUrl = new URL(String.format("%s/%s", hostName, fileName));
InputStream remoteInputStream remoteUrl.openConnection().getInputStream();
//copyStreamToFile(remoteInputStream, new File(destinationPath), false);

如果您希望文件对于库或代码来说是本地的,那么您不希望更改,可以:

void copyStreamToFile(InputStream in, File outputFile, boolean doDeleteOnExit) {
    //Clean up file after VM exit, if needed.
    if(doDeleteOnExit)
        outputFile.deleteOnExit();
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    ReadableByteChannel inputChannel = Channels.newChannel(in);
    WritableByteChannel outputChannel = Channels.newChannel(outputStream);
    ChannelTools.fastChannelCopy(inputChannel, outputChannel);
    inputChannel.close();
    outputChannel.close()
}

编辑使用JCIFS通过Samba访问远程文件非常简单:

domain = ""; //Your domain, only set if needed.
NtlmPasswordAuthentication npa = new NtlmPasswordAuthentication(domain, userName, password);
SmbFile remoteFile =  new SmbFile(String.format("smb://%s/%s", hostName, fileName), npa);
//copyStreamToFile(new SmbFileInputStream(remoteFile), new File(destinationPath), false)

这可能是最实用的解决方案,因为它在Windows服务器上需要的工作量最少。 这将插入Windows中现有的服务器框架,而不是安装更多服务器。

暂无
暂无

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

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