java操作ftp

本文介绍了一个名为FtpUtil的Java类,该类提供了一系列用于与FTP服务器交互的方法,包括连接服务器、上传和下载文件、获取目录文件列表及创建目录等。通过示例展示了如何使用该类完成基本的FTP操作。
package com.centralsoft.lms.common;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class FtpUtil {
	
	private FtpClient ftpClient;
	/**
	 * connectServer 连接ftp服务器
	 * 
	 * @throws java.io.IOException
	 * @param path
	 *            文件夹,空代表根目录
	 * @param password
	 *            密码
	 * @param user
	 *            登陆用户
	 * @param server
	 *            服务器地址
	 */
	public void connectServer(String server, String user, String password,
			String path) throws IOException {
		// server:FTP服务器的IP地址;user:登录FTP服务器的用户名
		// password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径
		ftpClient = new FtpClient();
		ftpClient.openServer(server);
		ftpClient.login(user, password);
		// path是ftp服务下主目录的子目录
		if (path.length() != 0){
			if(!this.isDirExist(path)){
				this.createDir(path);//目录不存在则创建
			} 
			
			ftpClient.cd(path);
		}
			
		// 用2进制上传、下载
		ftpClient.binary();
	}
	/**
	 * upload 上传文件
	 * 
	 * @throws java.lang.Exception
	 * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
	 * @param newname
	 *            上传后的新文件名
	 * @param filename
	 *            上传的文件
	 */
	public long upload(String filename, String newname) throws Exception {
		long result = 0;
		TelnetOutputStream os = null;
		FileInputStream is = null;
		try {
			java.io.File file_in = new java.io.File(filename);
			if (!file_in.exists())
				return -1;
			if (file_in.length() == 0)
				return -2;
			os = ftpClient.put(newname);
			result = file_in.length();
			is = new FileInputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
		return result;
	}
	/**
	 * upload
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param filename
	 */
	public long upload(String filename) throws Exception {
		String newname = "";
		if (filename.indexOf("/") > -1) {
			newname = filename.substring(filename.lastIndexOf("/") + 1);
		} else {
			newname = filename;
		}
		return upload(filename, newname);
	}
	/**
	 * download 从ftp下载文件到本地
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename
	 *            本地生成的文件名
	 * @param filename
	 *            服务器上的文件名
	 */
	public long download(String filename, String newfilename) throws Exception {
		long result = 0;
		TelnetInputStream is = null;
		FileOutputStream os = null;
		try {
			is = ftpClient.get(filename);
			java.io.File outfile = new java.io.File(newfilename);
			os = new FileOutputStream(outfile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
				result = result + c;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
		return result;
	}
	/**
	 * 取得某个目录下的所有文件列表
	 * 
	 */
	public List getFileList(String path) {
		List list = new ArrayList();
		try {
			DataInputStream dis = new DataInputStream(ftpClient.nameList(path));
			String filename = "";
			while ((filename = dis.readLine()) != null) {
				list.add(filename);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * closeServer 断开与ftp服务器的链接
	 * 
	 * @throws java.io.IOException
	 */
	public void closeServer() throws IOException {
			if (ftpClient != null) {
				ftpClient.closeServer();
			}
	}
	 /**
     * 检查文件夹在当前目录下是否存在
     * @param dir
     * @return
     */
     private boolean isDirExist(String dir){
         String pwd = "";
         try {
             pwd = ftpClient.pwd();
             ftpClient.cd(dir);
             ftpClient.cd(pwd);
         }catch(Exception e){
             return false;
         }
         return true;
     }

    /**
     * 在当前目录下创建文件夹
     * @param dir
     * @return
     * @throws Exception
     */
     private boolean createDir(String dir){
         try{
            ftpClient.ascii();
            StringTokenizer s = new StringTokenizer(dir, "/"); //sign
            s.countTokens();
            String pathName = ftpClient.pwd();
            while(s.hasMoreElements()){
                pathName = pathName + "/" + (String) s.nextElement();
                try {
                    ftpClient.sendServer("MKD " + pathName + "\r\n");
                } catch (Exception e) {
                    e = null;
                    return false;
                }
                ftpClient.readServerResponse();
            }
            ftpClient.binary();
            return true;
        }catch (IOException e1){
            e1.printStackTrace();
            return false;
        }
     }

	//test
	public static void main(String[] args) throws Exception {
		FtpUtil ftp = new FtpUtil();
		try {
			ftp.connectServer("10.1.10.5", "hj.xu", "iuDkXF", "/test/ttt/");
			ftp.upload("D:/aera.sql", "area.sql");
			ftp.closeServer();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Java中,你可以使用第三方库如Apache Commons Net或者FTPClient4J来进行FTP(File Transfer Protocol)服务器的操作。以下是一个简单的示例,展示如何连接、上传、下载以及断开FTP连接: 首先,你需要在项目中添加相应的依赖。例如,对于Apache Commons Net,你可以在pom.xml中添加: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> ``` 然后,你可以使用以下代码片段进行基本操作: ```java import org.apache.commons.net.ftp.*; public class FTPOperations { private FtpClient client; public void connect(String host, int port, String user, String password) throws IOException { client = new FtpClient(); client.connect(host, port); client.login(user, password); } public void uploadFile(String localFilePath, String remoteFilePath) throws IOException { FileInputStream fis = new FileInputStream(localFilePath); client.storeFile(remoteFilePath, fis); fis.close(); } public void downloadFile(String remoteFilePath, String localFilePath) throws IOException { InputStream fis = client.retrieveFileStream(remoteFilePath); FileOutputStream fos = new FileOutputStream(localFilePath); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } fos.close(); fis.close(); } public void disconnect() throws IOException { client.logout(); client.disconnect(); } public static void main(String[] args) { try { FTPOperations ftp = new FTPOperations(); // 连接到FTP服务器 ftp.connect("ftp.example.com", 21, "username", "password"); // 执行上传、下载等操作 ftp.uploadFile("/path/to/local/file.txt", "/remote/file.txt"); ftp.downloadFile("/remote/file.txt", "/path/to/download/file.txt"); // 断开连接 ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值