java ftp上传方法

提供一个思路,大家可以参考着修改自己的方法!   

/**
     * 上传文件到FTP
     *
     * @param file
     *            file文件,struts2从页面得到的File类型
     *
     * @param filePath
     *            要保存在FTP上的路径(文件夹)
     * @param fileName
     *         
     *
     * @return 文件是否上传成功
     *
     * @throws Exception
     */

    public static boolean upload(File file, String filePath, String fileName) {

        TelnetOutputStream to = null;

        FileInputStream fi = null;

        filePath = FILE_SEPARATOR (定义的路径获取)+ filePath;

        try {
            if (file != null) {

                connectFTP();
                // ftpClient.setAsciiType();

                if (!isDirExist(filePath.replace("\\", "/"))) {

                    createDir(filePath.replace("\\", "/"));

                    ftpClient.changeDirectory("/" + filePath.replace("\\", "/"));

                }

                fi = new FileInputStream(file);

                to = (TelnetOutputStream) ftpClient.putFileStream(fileName, true);

                byte[] bytes = new

                byte[1024];

                int i = fi.read(bytes);

                while (i != -1) {

                    to.write(bytes);

                    i = fi.read(bytes);
                }
            }

            return true;

        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
            return false;

        } catch (IOException e2) {
            e2.printStackTrace();
            return false;

        } catch (Exception e) {
            e.printStackTrace();
            return false;

        } finally {

            if (fi != null) {

                try {
                    fi.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (to != null) {

                try {
                    to.flush();

                    to.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            closeFTP();

        }

    }

 

    /**
     * 链接FTP
     *
     * @throws FtpProtocolException
     */

    public static void connectFTP() throws

    FtpProtocolException {

        try

        {

            ftpClient = FtpClient.create();

            ftpClient.connect(new InetSocketAddress(url, port));

            ftpClient.login(user, password.toCharArray());

            ftpClient.setBinaryType();

        } catch

        (IOException e) {

            e.printStackTrace();

        }

    }

转载于:https://my.oschina.net/maojindaoGG/blog/1613257

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值