一个很简单的用java上传FTP文件的实例程序,因为并不经常用,所以写下来以备用时参考 。
该实例程序部分包括三个类:FTPConfig、FTPHelper和Client,分别描述如下:
FTPConfig:FTP服务器的配置信息,包括服务器IP,用户名和密码。该信息从FTPHelper分离出来以便配置,代码如下:
package
qinysong.ftp;
public class FTPConfig ... {
public static final String FTP_SERVER_IP = "127.0.0.1";
public static final String FTP_SERVER_USER = "qinysong";
public static final String FTP_SERVER_PASS = "123456";
}
public class FTPConfig ... {
public static final String FTP_SERVER_IP = "127.0.0.1";
public static final String FTP_SERVER_USER = "qinysong";
public static final String FTP_SERVER_PASS = "123456";
}
FTPHelper:上传文件的帮助类,代码如下:
package
qinysong.ftp;
import java.io.IOException;
import java.io.FileInputStream;
import sun.net.ftp.FtpClient;
import sun.net.TelnetOutputStream;
public class FTPHelper ... {
public static void ftpTransmit(String localFile, String remoteFile) throws IOException ...{
System.out.println("FTPHelper.ftpTransmit begin ......");
FtpClient ftpClient = new FtpClient(FTPConfig.FTP_SERVER_IP);
ftpClient.login(FTPConfig.FTP_SERVER_USER, FTPConfig.FTP_SERVER_PASS);
FileInputStream fIs = new FileInputStream(localFile);
TelnetOutputStream tOs = ftpClient.put(remoteFile);
int readLength = 0;
byte[] bytes = new byte[1024];
while ( (readLength = fIs.read(bytes)) != -1) ...{
tOs.write(bytes, 0, readLength);
}
fIs.close();
tOs.close();
System.out.println("FTPHelper.ftpTransmit end ......");
}
}
import java.io.IOException;
import java.io.FileInputStream;
import sun.net.ftp.FtpClient;
import sun.net.TelnetOutputStream;
public class FTPHelper ... {
public static void ftpTransmit(String localFile, String remoteFile) throws IOException ...{
System.out.println("FTPHelper.ftpTransmit begin ......");
FtpClient ftpClient = new FtpClient(FTPConfig.FTP_SERVER_IP);
ftpClient.login(FTPConfig.FTP_SERVER_USER, FTPConfig.FTP_SERVER_PASS);
FileInputStream fIs = new FileInputStream(localFile);
TelnetOutputStream tOs = ftpClient.put(remoteFile);
int readLength = 0;
byte[] bytes = new byte[1024];
while ( (readLength = fIs.read(bytes)) != -1) ...{
tOs.write(bytes, 0, readLength);
}
fIs.close();
tOs.close();
System.out.println("FTPHelper.ftpTransmit end ......");
}
}
Client:FTPHelper的客户端,调用FTPHelper以上传文件,代码如下:
package
qinysong.ftp;
import java.io.IOException;
public class Client ... {
public static void main(String[] args) ...{
System.out.println("Client.main begin ......");
try ...{
FTPHelper.ftpTransmit("myfile20060824.txt", "myfile20060825.txt");
} catch (IOException ex1) ...{
ex1.printStackTrace();
}
System.out.println("Client.main end ......");
}
}
import java.io.IOException;
public class Client ... {
public static void main(String[] args) ...{
System.out.println("Client.main begin ......");
try ...{
FTPHelper.ftpTransmit("myfile20060824.txt", "myfile20060825.txt");
} catch (IOException ex1) ...{
ex1.printStackTrace();
}
System.out.println("Client.main end ......");
}
}