使用带有网络路径或驱动器的 Java 将文件写入远程位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18245766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a file to a remote location using Java with network path or drive?
提问by ohseekay
I have shared a folder on my server using Windows sharing. On another computer, where I am running my code on, I have mapped a network drive pointing to that folder.
我使用 Windows 共享在我的服务器上共享了一个文件夹。在另一台运行代码的计算机上,我映射了一个指向该文件夹的网络驱动器。
In my code, I transfer files from my local computer to my server every now and then. Something like this:
在我的代码中,我不时地将文件从本地计算机传输到我的服务器。像这样的东西:
File srcFile = new File("C:\test.mpg");
File destFile = new File(...);
// error checking
FileUtils.moveFile(srcFile, destFile);
For destFile
, which approach should I use? My current approach:
对于destFile
,我应该使用哪种方法?我目前的做法:
File destFile = new File("Z:\folder\test.mpg");
or using a network path:
或使用网络路径:
File destFile = new File("\192.168.123.123\folder\test.mpg");
I ask this because recently I have encountered cases where the file transfer fails because my program is unable to write to my network drive because it is not logged on, and I have to manually go to the drive and enter my credentials and enable "Stay connected" option.
我问这个是因为最近我遇到了文件传输失败的情况,因为我的程序无法写入我的网络驱动器,因为它没有登录,我必须手动转到驱动器并输入我的凭据并启用“保持连接” “ 选项。
回答by chrylis -cautiouslyoptimistic-
You can use mapped drives or full network paths equivalently; Java doesn't care and just passes the file name on to the OS. Note that if you're using a network path, you need \\\\
at the beginning.
您可以等效地使用映射驱动器或完整网络路径;Java 不在乎,只是将文件名传递给操作系统。请注意,如果您使用的是网络路径,则需要\\\\
在开头。
回答by Ahsan Shah
You can use the JCIFSlibrary to access a Windows SMB share in Java. Using it, you could do something like the following:
您可以使用JCIFS库访问 Java 中的 Windows SMB 共享。使用它,您可以执行以下操作:
String smbUrl = "smb://username:password@server/share/file";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL));