2012-07-31 95 views
4

我试着去开发一个简单的Java代码,将上传从本地机器的一些内容到服务器/另一machine.I用下面的代码文件上传

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'。 有人可以帮助我如何纠正它。

+0

您可以尝试使用apache的[FtpClient#storeFile](http://commons.apache.org/net/apidocs/org/apache/commons/net/ftp/FTPClient.html) – Arvik 2012-07-31 11:38:19

回答

2

你不能实例化它,因为sun.net.ftp.FtpClient是抽象类。

我建议使用Apache Commons Net而不是使用sun.x软件包。 FTP客户端示例可以从here找到。

+0

尝试了您建议的链接。但出错'导入org.apache无法解析' – Satheesh 2012-07-31 12:08:16

+0

它不是JDK的一部分,它是外部库。因此你也需要类库中的库本身。你可以从这里下载:http://commons.apache.org/net/download_net.cgi – 2012-07-31 12:10:13

+0

这真的帮助..现在我已经做了这样的FTPClient客户端=新的FTPClient(); FileInputStream fis = null; 尝试client.connect(“某个主机名称”); client.login(“user”,“pwd”); String filename =“Touch.dat”; fis = new FileInputStream(filename); client.storeFile(filename,fis); client.logout(); }当我给服务器主机和它的用户名和pwd..it抛出java.net.UnknownHostException..any想法回合呢? – Satheesh 2012-07-31 12:52:12

2

如果你想想要使用Sun类,请使用FtpClient.create(),根据该类的JavaDoc。

0

我已经解决了exception.thats,因为我的机器连接在一个不允许FTP连接的网络中。当我在一个专用加密狗中尝试它时,它工作。