设为首页 收藏本站
查看: 1414|回复: 0

[经验分享] 转 java通过ftp上传、下载文件,遍历文件目录

[复制链接]

尚未签到

发表于 2016-6-10 10:22:36 | 显示全部楼层 |阅读模式
001import java.io.DataInputStream;

002import java.io.File;

003import java.io.FileInputStream;

004import java.io.FileOutputStream;

005import java.io.IOException;

006import java.util.ArrayList;

007import java.util.List;

008 

009import org.apache.catalina.tribes.util.Logs;

010 

011import sun.net.TelnetInputStream;

012import sun.net.TelnetOutputStream;

013import sun.net.ftp.FtpClient;

014 

015public class DownFileForFtp {

016    FtpClient ftpClient;

017    private String server = "ip";

018    private int port = 21;

019    private String userName = "usn";

020    private String userPassword = "pwd";

021 

022    /**

023     * 链接到服务器

024     *

025     * @return

026     */

027    public boolean open() {

028        if (ftpClient != null && ftpClient.serverIsOpen())

029            return true;

030        try {

031            ftpClient = new FtpClient();

032            ftpClient.openServer(server, port);

033            ftpClient.login(userName, userPassword);

034            ftpClient.binary();

035            return true;

036        } catch (Exception e) {

037            e.printStackTrace();

038            ftpClient = null;

039            return false;

040        }

041    }

042 

043    public boolean cd(String dir) {

044        boolean f = false;

045        try {

046            ftpClient.cd(dir);

047        } catch (IOException e) {

048            //Logs.error(e.toString());

049            return f;

050        }

051        return true;

052    }

053 

054    /**

055     * 上传文件到FTP服务器

056     *

057     * @param localPathAndFileName

058     *            本地文件目录和文件名

059     * @param ftpFileName

060     *            上传后的文件名

061     * @param ftpDirectory

062     *            FTP目录如:/path1/pathb2/,如果目录不存在回自动创建目录

063     * @throws Exception

064     */

065    public boolean upload(String localDirectoryAndFileName, String ftpFileName,

066            String ftpDirectory) throws Exception {

067        if (!open())

068            return false;

069        FileInputStream is = null;

070        TelnetOutputStream os = null;

071        try {

072            char ch = ' ';

073            if (ftpDirectory.length() > 0)

074                ch = ftpDirectory.charAt(ftpDirectory.length() - 1);

075            for (; ch == '/' || ch == '\\'; ch = ftpDirectory

076                    .charAt(ftpDirectory.length() - 1))

077                ftpDirectory = ftpDirectory.substring(0,

078                        ftpDirectory.length() - 1);

079 

080            int slashIndex = ftpDirectory.indexOf(47);

081            int backslashIndex = ftpDirectory.indexOf(92);

082            int index = slashIndex;

083            String dirall = ftpDirectory;

084            if (backslashIndex != -1 && (index == -1 || index > backslashIndex))

085                index = backslashIndex;

086            String directory = "";

087            while (index != -1) {

088                if (index > 0) {

089                    String dir = dirall.substring(0, index);

090                    directory = directory + "/" + dir;

091                    ftpClient.sendServer("XMKD " + directory + "\r\n");

092                    ftpClient.readServerResponse();

093                }

094                dirall = dirall.substring(index + 1);

095                slashIndex = dirall.indexOf(47);

096                backslashIndex = dirall.indexOf(92);

097                index = slashIndex;

098                if (backslashIndex != -1

099                        && (index == -1 || index > backslashIndex))

100                    index = backslashIndex;

101            }

102            ftpClient.sendServer("XMKD " + ftpDirectory + "\r\n");

103            ftpClient.readServerResponse();

104 

105            os = ftpClient.put(ftpDirectory + "/" + ftpFileName);

106            File file_in = new File(localDirectoryAndFileName);

107            is = new FileInputStream(file_in);

108            byte bytes[] = new byte[1024];

109            int i;

110            while ((i = is.read(bytes)) != -1)

111                os.write(bytes, 0, i);

112            // 清理垃圾

113 

114            return true;

115        } catch (Exception e) {

116            e.printStackTrace();

117            return false;

118        } finally {

119            if (is != null)

120                is.close();

121            if (os != null)

122                os.close();

123        }

124    }

125 

126    /**

127     * 从FTP服务器上下载文件并返回下载文件长度

128     *

129     * @param ftpDirectoryAndFileName

130     * @param localDirectoryAndFileName

131     * @return

132     * @throws Exception

133     */

134    public long download(String ftpDirectoryAndFileName,

135            String localDirectoryAndFileName) throws Exception {

136        long result = 0;

137        if (!open())

138            return result;

139        TelnetInputStream is = null;

140        FileOutputStream os = null;

141        try {

142            is = ftpClient.get(ftpDirectoryAndFileName);

143            java.io.File outfile = new java.io.File(localDirectoryAndFileName);

144            os = new FileOutputStream(outfile);

145            byte[] bytes = new byte[1024];

146            int c;

147            while ((c = is.read(bytes)) != -1) {

148                os.write(bytes, 0, c);

149                result = result + c;

150            }

151        } catch (Exception e) {

152            throw e;

153        } finally {

154            if (is != null)

155                is.close();

156            if (os != null)

157                os.close();

158 

159        }

160        return result;

161    }

162 

163    /**

164     * 返回FTP目录下的文件列表

165     *

166     * @param ftpDirectory

167     * @return

168     */

169    public List<String> getFileNameList(String ftpDirectory) {

170        List<String> list = new ArrayList<String>();

171        if (!open())

172            return list;

173        try {

174            DataInputStream dis = new DataInputStream(

175                    ftpClient.nameList(ftpDirectory));

176            String filename = "";

177            while ((filename = dis.readLine()) != null) {

178                list.add(filename);

179                System.out.println(filename);

180            }

181        } catch (Exception e) {

182            e.printStackTrace();

183        }

184        return list;

185    }

186 

187    /**

188     * 删除FTP上的文件

189     *

190     * @param ftpDirAndFileName

191     */

192    public boolean deleteFile(String ftpDirAndFileName) {

193        if (!open())

194            return false;

195        ftpClient.sendServer("DELE " + ftpDirAndFileName + "\r\n");

196        return true;

197    }

198 

199    /**

200     * 删除FTP目录

201     *

202     * @param ftpDirectory

203     */

204    public boolean deleteDirectory(String ftpDirectory) {

205        if (!open())

206            return false;

207        ftpClient.sendServer("XRMD " + ftpDirectory + "\r\n");

208        return true;

209    }

210 

211    /**

212     * 关闭链接

213     */

214    public void close() {

215        try {

216            if (ftpClient != null && ftpClient.serverIsOpen())

217                ftpClient.closeServer();

218        } catch (Exception e) {

219 

220        }

221    }

222     

223    public static void main(String []args) throws Exception{

224        DownFileForFtp df = new DownFileForFtp();

225        df.getFileNameList("E:\\uploadfiles\\cat");

226        df.download("E:\\uploadfiles\\cat\\2012-03-29.11.00.00.012.xml", "F:\\temp\\ftpdown\\2012-03-29.11.00.00.012.xml");

227 

228    }

229     

230}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228538-1-1.html 上篇帖子: 批处理下载FTP服务器上某个目录下的文件 下篇帖子: 秒杀398上传图片到ftp卡住的问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表