利用JAVA写一段上传文件程序(模拟Ftp客户端)

package com.hellojim.beans;

import sun.net.ftp.*;
import java.util.*;
import sun.net.*;
import java.io.*;

public class FtpTest {
	
	public static void main(String[] args) throws IOException {
		
			byte[] bt = null;
			TelnetInputStream getfile;
			TelnetOutputStream putfile;
			String str;
			
			// 和服务器建立连接,这里的服务器为公司局域网内的一台机器,IP为 192.168.1.46
			FtpClient ftp = null;
			try {
				ftp = new FtpClient("192.168.1.46");
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			str = ftp.getResponseString();
			//这里的 getResponseString() 为每操作一步,服务器响应的信息,打印这样的信息,有助于调试程序
			System.out.println("step 1:" + str);

			/**
			 * 登陆到Ftp服务器
			 */
			try {
				/**登录到Ftp服务器,这里的用户名(hellojim)和密码(sa)都是事先在192.168.1.46
				 * 这台机器的Ftp服务器端的Serv-U上添加的,hellojim这个用户的权限已在Serv-U上
				 * 定义过了(比如对某个文件夹的访问权限啊,只能访问那些目录...),
				 * 以我的机器为例吧:hellojim这个用户登录上去后,服务器端显示的目录为d:\,并且
				 * d:\ 下有一个名为 test 的目录
				 */
				ftp.login("hellojim", "sa");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			str = ftp.getResponseString();
			System.out.println("step 2:" + str);

			/**
			 * 下面的代码是打印当前目录列表
			 */
			TelnetInputStream in = null;
			try {
				in = ftp.list();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			str = ftp.getResponseString();
			System.out.println("step 3:" + str);
			
			try {
				bt = new byte[in.available()];
				in.read(bt);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			str = new String(bt);
			System.out.println("step 4:" + str );
			try {
				//cd() 方法用来改变当前目录
				ftp.cd("test");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			str = ftp.getResponseString();
			System.out.println("step 5:" + str);

			/**
			 * 下面的代码是打印test目录列表
			 */
			in = ftp.list();
			str = ftp.getResponseString();
			System.out.println("step 6:" + str);
			bt = new byte[in.available()];
			in.read(bt);
			str = new String(bt);
			System.out.println("step 7:" + str);
			str = ftp.getResponseString();
			System.out.println("step 8:" + str);
			
			ftp.binary(); //上载二进制文件的代码,如果是上传文本文件的可是写成 ftp.ascii();
			//zhangsan.doc 表示上传到服务器上后,这个文件的名字
			putfile = ftp.put("zhangsan.doc");
			//d:\\lisi.doc 表示上传的本地文件
			FileInputStream fs = new FileInputStream("d:\\lisi.doc");
			while (true) {
				int i = fs.read();
				if (i == -1)
					break;
				else {
					putfile.write((byte) i);
					putfile.flush();
				}
			}
			putfile.close();
			fs.close();

	}
}
//附件中有具体的例子

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值