Java Ftp 操作上传与下载

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.apache.commons.net.ftp.FTPClient; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; public class Test { private String ip = "192.168.5.200"; private int poot = 21; private String userName = "weizheng"; private String password = "123456"; private String oldFilePath = "C://Users//Administrator//Desktop//aaa.doc"; private String newFileName = "123456.doc"; private String dowloadPath = "F:/"+newFileName; private void apacheUpload() throws Exception{ FTPClient client = new FTPClient(); FileInputStream fis = null; client.connect(ip); client.login(userName, password); File srcFile = new File(oldFilePath); fis = new FileInputStream(srcFile); //设置上传目录 client.changeWorkingDirectory("/"); client.setBufferSize(1024); client.setControlEncoding("GBK"); //设置文件类型(二进制) client.setFileType(FTPClient.BINARY_FILE_TYPE); client.storeFile("abc.doc", fis); IOUtils.closeQuietly(fis); try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); } } private void apacheDowload() throws Exception{ FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { ftpClient.connect(ip); ftpClient.login(userName, password); fos = new FileOutputStream(dowloadPath); ftpClient.setBufferSize(1024); //设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.retrieveFile(oldFilePath, fos); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("FTP客户端出错!", e); } finally { IOUtils.closeQuietly(fos); try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); } } } private void sunUpload() throws Exception{ FtpClient sunClient = new FtpClient(); TelnetOutputStream os = null; FileInputStream is = null; sunClient.openServer(ip); sunClient.login(userName, password); os = sunClient.put(newFileName); File file = new File(oldFilePath); is = new FileInputStream(file); byte[] b = new byte[1024]; int len = 0; while((len=is.read(b))!=-1){ os.write(b,0,len); } is.close(); os.close(); } private void sunDownload() throws Exception{ FtpClient sunClient = new FtpClient(); TelnetInputStream is = null; FileOutputStream os = null; sunClient.openServer(ip); sunClient.login(userName, password); is = sunClient.get(newFileName); File outputfile = new File(dowloadPath); os = new FileOutputStream(outputfile); byte[] b = new byte[1024]; int len = 0; while((len=is.read(b))!=-1){ os.write(b, 0, len); } is.close(); os.close(); } public static void main(String[] args) throws Exception { Test t = new Test(); t.sunUpload(); t.sunDownload(); // t.apacheUpload(); // t.apacheDowload(); } }

其中apache方式操作需要添加 jar

    commons-io.jar

    commons-net..jar

你可能感兴趣的:(Java Ftp 操作上传与下载)