通过FTP在Java中上传文件
我正在尝试开发一个简单的java代码,将一些内容从本地机器上传到服务器/另一台机器通过FTP在Java中上传文件,java,upload,ftp,Java,Upload,Ftp,我正在尝试开发一个简单的java代码,将一些内容从本地机器上传到服务器/另一台机器 import sun.net.ftp.*; import java.io.*; public class SftpUpload { public static void main(String args[]) { String hostname = "some.remote.machine"; //Remote FTP server: Change this String username = "
import sun.net.ftp.*;
import java.io.*;
public class SftpUpload {
public static void main(String args[]) {
String hostname = "some.remote.machine"; //Remote FTP server: Change this
String username = "user"; //Remote user name: Change this
String password = "start123"; //Remote user password: Change this
String upfile = args[0]; //File to upload passed on command line
String remdir = "/home/user"; //Remote directory for file upload
FtpClient ftp = new FtpClient();
try {
ftp.openServer(hostname); //Connect to FTP server
ftp.login(username, password); //Login
ftp.binary(); //Set to binary mode transfer
ftp.cd(remdir); //Change to remote directory
File file = new File(upfile);
OutputStream out = ftp.put(file.getName()); //Start upload
InputStream in = new FileInputStream(file);
byte c[] = new byte[4096];
int read = 0;
while ((read = in.read(c)) != -1 ) {
out.write(c, 0, read);
} //Upload finished
in.close();
out.close();
ftp.closeServer(); //Close connection
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
但它在第11行显示错误,因为“无法实例化FtpClient类型”。
有人能帮我纠正一下吗。您不能实例化它,因为sun.net.ftp.FtpClient是抽象类
我建议使用ApacheCommonsNet,而不是使用sun.x软件包。FTP客户端示例可从中找到。如果您确实想使用Sun类,请使用
FtpClient.create()
,根据这个类的JavaDoc。我已经解决了这个异常。这是因为我的机器连接在一个不允许FTP连接的网络中。当我在一个私有加密狗中尝试它时,它工作了。你可以尝试使用apache尝试你建议的链接。但是出现错误“导入org.apache无法解决”,它不是JDK,它是外部库。因此,在类路径中还需要库本身。你可以从这里下载:这真的很有帮助。。现在我已经做了类似于FTPClient client=new FTPClient()的事情;FileInputStream fis=null;尝试{client.connect(“某些主机名”);client.login(“用户”,“pwd”);String filename=“Touch.dat”;fis=new FileInputStream(文件名);client.storeFile(文件名,fis);client.logout();}当我给出服务器主机及其用户名和pwd时..它抛出java.net.UnknownHostException..你知道吗?