1.Java进行FTP操作所需要的jar包
- import org.apache.commons.io.IOUtils;
- import org.apache.commons.net.ftp.FTPClient;
2.上传文件到FTP
- public boolean saveInFTP (String reTransmitFolderName, String reTransmitFileName, byte[] data) {
- boolean flag = false;
- // 创建FTP客户端
- FTPClient ftpClient = new FTPClient();
- // 输入流用于读取文件
- // FileInputStream fis = null;
- ByteArrayInputStream bis = null;
- try {
- if (reTransmitFolderName != null
- && reTransmitFolderName.compareTo("") != 0
- && reTransmitFileName != null
- && reTransmitFileName.compareTo("") != 0) {
- // 建立FTP连接
- ftpClient.connect(this.ftpServerIP);
- // 如果登录成功后, 才进行创建输入流
- if (ftpClient.login(this.ftpName, this.ftpPassword)) {
- // File srcClientFile = new File("C:/ParseXML.xml");
- // 实例化输入流
- // fis = new FileInputStream(srcClientFile);
- if (ftpClient.changeWorkingDirectory(reTransmitFolderName)) {
- // 将byte[]写入到输入流中, 实例化
- bis = new ByteArrayInputStream(data);
- // 设置缓冲
- ftpClient.setBufferSize(RetransmitStateDefine.BUFFER_SIZE);
- // 设置文件类型(二进制类型)
- if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) {
- flag = ftpClient.storeFile(reTransmitFileName, bis);
- }
- }
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- flag = false;
- } catch (IOException e) {
- e.printStackTrace();
- flag = false;
- } catch (Exception e) {
- e.printStackTrace();
- flag = false;
- } finally {
- try {
- // 关闭输入流
- IOUtils.closeQuietly(bis);
- // 关闭连接
- ftpClient.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return flag;
- }
3.从FTP上读取文件
- public boolean getFromFTP () {
- boolean flag = false;
- // 创建FTP客户端
- FTPClient ftpClient = new FTPClient();
- // 用于输出文件
- FileOutputStream fos = null;
- try {
- // 建立FTP连接
- ftpClient.connect(this.ftpServerIP);
- // 如果登录成功
- if (ftpClient.login(this.ftpName, this.ftpPassword)) {
- // FTP文件
- String distinationFile = "/xxx_xx/xxx/ParseXML_InFTP.xml";
- // 实例化输出流
- fos = new FileOutputStream("C:/ParseXML_InFTP.xml");
- // 设置缓冲
- ftpClient.setBufferSize(RetransmitStateDefine.BUFFER_SIZE);
- // 设置文件类型(二进制类型)
- if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) {
- ftpClient.retrieveFile(distinationFile, fos);
- flag = true;
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- flag = false;
- } catch (IOException e) {
- e.printStackTrace();
- flag = false;
- } catch (Exception e) {
- e.printStackTrace();
- flag = false;
- } finally {
- try {
- // 关闭输出流
- IOUtils.closeQuietly(fos);
- // 关闭连接
- ftpClient.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return flag;
- }
转载自: http://blog.csdn.net/android_robot/article/details/7094393