我想在java中将文件从服务器复制到客户端。这是我的代码到目前为止
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
问题是,服务器没有在线上传,但它在我的本地驱动器上,并且URL不起作用。还有其他方法吗?这样正确吗?感谢
答案 0 :(得分:0)
如果您希望从本地文件系统访问您的文件(无论是通过网络驱动器还是本地磁盘),您需要将其视为直接文件副本。
如果您希望访问您的文件,就好像它可以从HTTP服务器下载一样,您将需要将其视为HTTP下载(这就是您尝试使用URL进行的操作)。
如果要使用本地系统上的文件测试HTTP下载功能,只需在您的开发计算机上使用本地系统上的目录设置一个简单的HTTP服务器,并为您的HTTP下载代码提供指向的URL本地服务器(在http://localhost上,或使用您的IP地址)。
不幸的是,HTTP是一个与文件系统截然不同的动物,我认为没有办法使用相同的代码来处理这两种情况。如果您希望程序最终支持这两种协议,则应构建方法/类来处理这两种情况,然后让程序检测并使用适当的协议来处理给定路径。您需要为您希望支持的任何其他协议(FTP,SFTP等)执行相同的操作。