简体   繁体   English

使用带网络路径或驱动器的Java将文件写入远程位置?

[英]Write a file to a remote location using Java with network path or drive?

I have shared a folder on my server using Windows sharing. 我使用Windows共享在我的服务器上共享了一个文件夹。 On another computer, where I am running my code on, I have mapped a network drive pointing to that folder. 在另一台运行我的代码的计算机上,我已经映射了一个指向该文件夹的网络驱动器。

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? 对于destFile ,我应该使用哪种方法? My current approach: 我目前的做法:

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. 我问这个是因为最近我遇到了文件传输失败的情况,因为我的程序无法写入我的网络驱动器,因为它没有登录,我必须手动转到驱动器并输入我的凭据并启用“保持连接” “ 选项。

You can use mapped drives or full network paths equivalently; 您可以等效地使用映射驱动器或完整网络路径; Java doesn't care and just passes the file name on to the OS. Java并不关心,只是将文件名传递给操作系统。 Note that if you're using a network path, you need \\\\\\\\ at the beginning. 请注意,如果您使用的是网络路径,则开头需要\\\\\\\\

You can use the JCIFS library to access a Windows SMB share in Java. 您可以使用JCIFS库访问Java中的Windows SMB共享。 Using it, you could do something like the following: 使用它,您可以执行以下操作:

String smbUrl = "smb://username:password@server/share/file";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL));

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

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