本文介紹了通過 FTP 在 Java 中上傳文件的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試開發一個簡單的 java 代碼,它將一些內容從本地機器上傳到服務器/另一臺機器.我使用了下面的代碼
Im trying to develop a simple java code which will upload some contents from local machine to a server/another machine.I used the below code
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 類型".誰能幫我解決一下.
But it is showing error in Line 11 as 'Cannot instantiate the type FtpClient'. Can some one help me how to rectify it.
推薦答案
你不能實例化它,因為 sun.net.ftp.FtpClient 是抽象類.
You cannot instantiate it because sun.net.ftp.FtpClient is abstract class.
我建議使用 Apache Commons Net 而不是使用 sun.x 包.FTP客戶端示例可以從這里找到.
I suggest using Apache Commons Net instead of playing with sun.x packages. FTP client example can be found from here.
這篇關于通過 FTP 在 Java 中上傳文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!