java跨服务器保存文件:jcifs & FTP
1.使用共享网络磁盘的形式,在当前的服务器简历一个另一台服务器的网络磁盘,直接操作读写这个网络磁盘即可
2.使用FTP操作另外这台服务器
帖子1:java上传图片到另一台服务器上,如何解决?
http://bbs.csdn.net/topics/370033090?page=1#post-394318586
使用org.apache.commons.net.ftp包开发FTP客户端,实现进度汇报,实现断点续传,中文支持
利用org.apache.commons.net.ftp包实现一个简单的ftp客户端实用类。主要实现一下功能
1.支持上传下载。支持断点续传
2.支持进度汇报
3.支持对于中文目录及中文文件创建的支持。
http://zhangnet1.iteye.com/blog/907109
两个工具:
1. 有人介绍用jcifs-1.1.11.jar,这个可以在远程服务器上创建文件夹
2. apache的ftp工具
3. java.net支持
通过jcifs实现java访问网络共享文件
在Microsoft 网 络 系 统 中,SMB(Server Message Block,服务信息块)协议是WindowsforWorkgroup(WfWg)、Windows95、WindowsNT和LanManager用来实现共享局域网上文件和打印机的协议。对于利用Linux和WindowsNT构建的局域网来说,Samba就是为Linux提供的SMB客户程序/服务器程序的软件包,其功能是实现Windows 和Linux互相共享对方的磁盘空间和打印机。通用网络文件系统简称CIFS,它事实上是windows平台文件共享的标准协议,它是windows explorer,网络邻居和映射网络驱动器的底层实现协议。JAVA具有天然的平台无关性,使用JAVA可以访问任何类型的服务器或客户机上的共享文件系统,并且编写的软件产品可以运行于任何平台,因此用JAVA访问共享文件系统在企业应用中具有得天独厚的优势。
jcifs是CIFS在JAVA中的一个实现,是samba组织负责维护开发的一个开源项目,专注于使用java语言对cifs协议的设计和实现。他们将jcifs设计成为一个完整的,丰富的,具有可扩展能力且线程安全的客户端库。这一库可以应用于各种java虚拟机访问遵循CIFS/SMB网络传输协议的网络资源。类似于java.io.File的接口形式,在多线程的工作方式下被证明是有效而容易使用的。
jcifs的开发方法类似java的文件操作功能,它的资源url定位:smb://{user}:{password}@{host}/{path},smb为协议名,user和password分别为共享文件机子的登陆名和密码,@后面是要访问的资源的主机名或IP地址。最后是资源的共享文件夹名称和共享资源名。例如 smb://administrator:122122@192.168.0.22/test/response.txt。
在JAVA程序中,使用如下方式获得一个远程共享文件的句柄:SmbFile file = new SmbFile(“smb://guest:1234@192.168.3.56/share/a.txt”);这里的句柄不仅限于远程的共享文件,还可能是共享文件夹。isFile()方法和isDirectory()用来判断这个句柄对应的资源的真实属性。如果是共享文件夹,通过调用它的list()方法将获得其中资源的列表。List方法支持过滤器机制,有两种过滤器可供使用,一种是SmbFileFilter,另一种是SmbFilenameFilter,这两个在jcifs中作为接口出现,你可以根据自己的需要派生出个性化的过滤器,实现接口中的accept方法,以满足不同业务的需求。
SmbFileInputStream是smb文件的输入流,它的功能是以流的方式打开一个SmbFile:SmbFileInputStream in = new SmbFileInputStream(file);SmbFileInputStream提供read方法,你可以从这个流中读出远程文件全部的内容。
SmbFileInputStream,SmbFileOutputStream,SmbFile这里对应着io里的FileInputStream
FileOutputStream,File,如果对io比较熟悉那么jcifs比较容易应用
下面一个最简单的例子说明jcifs的用法
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Java代码 import jcifs.smb.SmbFileInputStream; import jcifs.smb.SmbFile; public class ReadShareFile { public static void main(String[] args) { try{ SmbFile smbFile=new SmbFile("smb://test:test@10.218.100.12/share2/aa.txt"); //通过 smbFile.isDirectory();isFile()可以判断smbFile是文件还是文件夹 int length=smbFile.getContentLength();//得到文件的大小 byte buffer[] = new byte[length] ; SmbFileInputStream in = new SmbFileInputStream(smbFile) ; //建立smb文件输入流 while((in.read(buffer)) != -1){ System.out.write(buffer); System.out.println(buffer.length); } in.close(); }catch(Exception e){ e.printStackTrace(); } |
smb://guest:1234@192.168.3.56/share/a.txt
这个url的开始部分smb:// 说明了这是一个smb类型的url;接下来的guest和1234分别是访问共享资源的用户名称和密码;@后面是要访问的资源的主机名或IP地址。最后是资源的共享文件夹名称和共享资源名。
Commons Net, 这个包还是很实用的,封装了很多网络协议。
要设定二进制方式,否在一些文件不完整。
|
1 2 3 4 5 |
Java代码 //设置被动模式 ftpClient.enterLocalPassiveMode(); //设置以二进制方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); |
如果使用InputStream读取字节流,不能一次读写完, 要分次读取
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Java代码 InputStream in =ftpClient.retrieveFileStream(new String(downLoadFileName.getBytes("UTF-8"), "UTF-8")); //int size=in.available(); Long t = ftpFile.getSize(); int size=t.intValue(); byte[] buffer = new byte[t.intValue()]; byte[] tmp = new byte[1024]; int length = -1; int count=0; while ((length=in.read(tmp))!= -1) { System.arraycopy(tmp, 0, buffer, count, length); count=count+length; } is.write(buffer); in.close(); is.close(); |
例子1: 基于Apache Common-net Ftp实例 http://www.iteye.com/topic/1118804
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
Java代码 package com.shine.Ftp.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPListParseEngine; import org.apache.commons.net.ftp.FTPReply; public class FTPUtil { private FTPClient ftp = null; /** * Ftp服务器 */ private String server; /** * 用户名 */ private String uname; /** * 密码 */ private String password; /** * 连接端口,默认21 */ private int port = 21; public FTPUtil() { } /** * 连接FTP服务器 * * @param server * @param uname * @param password * @return * @throws Exception */ public FTPClient connectFTPServer(String server, int port, String uname, String password) throws Exception { //初始化并保存信息 this.server = server ; this.port = port ; this.uname = uname ; this.password = password ; ftp = new FTPClient(); try { ftp.configure(getFTPClientConfig()); ftp.connect(this.server, this.port); ftp.login(this.uname, this.password); // 文件类型,默认是ASCII ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置被动模式 ftp.enterLocalPassiveMode(); ftp.setConnectTimeout(2000); ftp.setControlEncoding("GBK"); // 响应信息 int replyCode = ftp.getReplyCode(); if ((!FTPReply.isPositiveCompletion(replyCode))) { // 关闭Ftp连接 closeFTPClient(); // 释放空间 ftp = null; throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、" + "User:" + uname + "、" + "Password:" + password); } else { return ftp; } } catch (Exception e) { ftp.disconnect(); ftp = null; throw e; } } /** * 配置FTP连接参数 * * @return * @throws Exception */ public FTPClientConfig getFTPClientConfig() throws Exception { String systemKey = FTPClientConfig.SYST_NT; String serverLanguageCode = "zh"; FTPClientConfig conf = new FTPClientConfig(systemKey); conf.setServerLanguageCode(serverLanguageCode); conf.setDefaultDateFormatStr("yyyy-MM-dd"); return conf; } /** * 上传文件到FTP根目录 * * @param localFile * @param newName * @throws Exception */ public void uploadFile(String localFile, String newName) throws Exception { InputStream input = null; try { File file = null; if (checkFileExist(localFile)) { file = new File(localFile); } input = new FileInputStream(file); boolean result = ftp.storeFile(newName, input); if (!result) { throw new Exception("文件上传失败!"); } } catch (Exception e) { throw e; } finally { if (input != null) { input.close(); } } } /** * 上传文件到FTP根目录 * * @param input * @param newName * @throws Exception */ public void uploadFile(InputStream input, String newName) throws Exception { try { boolean result = ftp.storeFile(newName, input); if (!result) { throw new Exception("文件上传失败!"); } } catch (Exception e) { throw e; } finally { if (input != null) { input.close(); } } } /** * 上传文件到指定的FTP路径下 * * @param localFile * @param newName * @param remoteFoldPath * @throws Exception */ public void uploadFile(String localFile, String newName, String remoteFoldPath) throws Exception { InputStream input = null; try { File file = null; if (checkFileExist(localFile)) { file = new File(localFile); } input = new FileInputStream(file); // 改变当前路径到指定路径 this.changeDirectory(remoteFoldPath); boolean result = ftp.storeFile(newName, input); if (!result) { throw new Exception("文件上传失败!"); } } catch (Exception e) { throw e; } finally { if (input != null) { input.close(); } } } /** * 上传文件到指定的FTP路径下 * * @param input * @param newName * @param remoteFoldPath * @throws Exception */ public void uploadFile(InputStream input, String newName, String remoteFoldPath) throws Exception { try { // 改变当前路径到指定路径 this.changeDirectory(remoteFoldPath); boolean result = ftp.storeFile(newName, input); if (!result) { throw new Exception("文件上传失败!"); } } catch (Exception e) { throw e; } finally { if (input != null) { input.close(); } } } /** * 从FTP指定的路径下载文件 * * @param remotePath * @param localPath */ public void downloadFile(String remotePath, String localPath) throws Exception { OutputStream output = null; try { File file = null; if (checkFileExist(localPath)) { file = new File(localPath); } output = new FileOutputStream(file); boolean result = ftp.retrieveFile(remotePath, output); if (!result) { throw new Exception("文件下载失败!"); } } catch (Exception e) { throw e; } finally { if (output != null) { output.close(); } } } /** * 从FTP指定的路径下载文件 * * @param remoteFilePath * @return * @throws Exception */ public InputStream downFile(String remoteFilePath) throws Exception { return ftp.retrieveFileStream(remoteFilePath); } /** * 获取FTP服务器上指定路径下的文件列表 * * @param filePath * @return */ public List<String> getFtpServerFileList(String filePath) throws Exception { List<String> nlist = new ArrayList<String>(); FTPListParseEngine engine = ftp.initiateListParsing(filePath); List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25)); return getFTPServerFileList(nlist,ftpfiles); } /** * 获取FTP服务器上指定路径下的文件列表 * @param path * @return * @throws Exception */ public List<String> getFileList(String path) throws Exception { List<String> nlist = new ArrayList<String>(); List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(path)); return getFTPServerFileList(nlist,ftpfiles); } /** * 列出FTP服务器文件列表信息 * @param nlist * @param ftpFiles * @return */ public List<String> getFTPServerFileList(List<String> nlist,List<FTPFile> ftpFiles){ if(ftpFiles==null || ftpFiles.size()==0) return nlist; for (FTPFile ftpFile : ftpFiles) { if (ftpFile.isFile()) { nlist.add(ftpFile.getName()); } } return nlist; } /** * 改变工作目录,如失败则创建文件夹 * * @param remoteFoldPath */ public void changeDirectory(String remoteFoldPath) throws Exception { if (remoteFoldPath != null) { boolean flag = ftp.changeWorkingDirectory(remoteFoldPath); if (!flag) { ftp.makeDirectory(remoteFoldPath); ftp.changeWorkingDirectory(remoteFoldPath); } } } /** * 检查文件是否存在 * * @param filePath * @return * @throws Exception */ public boolean checkFileExist(String filePath) throws Exception { boolean flag = false; File file = new File(filePath); if (!file.exists()) { throw new Exception("文件不存在,请检查!"); } else { flag = true; } return flag; } /** * 获取文件名,不包括后缀 * * @param filePath * @return */ public String getFileNamePrefix(String filePath) throws Exception { boolean flag = this.checkFileExist(filePath); if (flag) { File file = new File(filePath); String fileName = file.getName(); String _fileName = fileName.substring(0, fileName.lastIndexOf(".")); return _fileName; } return null; } /** * 关闭FTP连接 * * @param ftp * @throws Exception */ public void closeFTPClient(FTPClient ftp) throws Exception { try { if (ftp.isConnected()) ftp.disconnect(); } catch (Exception e) { throw new Exception("关闭FTP服务出错!"); } } /** * 关闭FTP连接 * * @throws Exception */ public void closeFTPClient() throws Exception { this.closeFTPClient(this.ftp); } /** * Get Attribute Method * */ public FTPClient getFtp() { return ftp; } public String getServer() { return server; } public String getUname() { return uname; } public String getPassword() { return password; } public int getPort() { return port; } /** * Set Attribute Method * */ public void setFtp(FTPClient ftp) { this.ftp = ftp; } public void setServer(String server) { this.server = server; } public void setUname(String uname) { this.uname = uname; } public void setPassword(String password) { this.password = password; } public void setPort(int port) { this.port = port; } /** * 主方法(测试) * * @param args */ public static void main(String[] args) { try { FTPUtil fu = new FTPUtil(); fu.connectFTPServer("192.168.11.28", 21, "Ftpuser", "sunshine"); } catch (Exception e) { System.out.println("异常信息:" + e.getMessage()); } } } |
例子2: 利用commons-net包实现ftp上传下载例子 http://sosuny.iteye.com/blog/888884
下载文件的时候注意一下,第一个参数要用iso-8859_1编码的,否则文件大小等于0!
直接贴图代码了:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
Java代码 package ftp2; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; /** * 使用commons的net包进行ftp链接. 相关包:commons-net-1.4.1.jar ; * commons-io-1.2.jar;jakarta-oro-2.0.8.jar测试通过.可以列出ftp上的文件 * 通过把ftp服务器上的文件流连接到outSteam及可以把文件下载到本机的目录..限制如果目录为中文则需要处理.最好使用英文文件名 * */ public class ListFtpFile { private FTPClient ftpClient = new FTPClient(); private OutputStream outSteam = null; /** * ftp服务器地址 */ private String hostName = "192.168.0.2"; private int port = 212; /** * 登录名 */ private String userName = "anonymous";//匿名登录 /** * 登录密码 */ private String password = "121@hotmail.com";//随便一个地址 /** * 需要访问的远程目录 */ private String remoteDir = "/software/dreamweaver/"; /** * 下载 */ private void download() { try { // 链接到ftp服务器 ftpClient.connect(hostName,port); System.out.println("连接到ftp服务器:" + hostName + " 成功..开始登录"); // 登录.用户名 密码 boolean b = ftpClient.login(userName, password); System.out.println("登录成功." + b); // 检测连接是否成功 int reply = ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftpClient.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir); if (remoteFiles != null) { for (int i = 0; i < remoteFiles.length; i++) { String name = remoteFiles[i].getName(); //下载 File localFile = new File("c:/001/ftp/" + name); OutputStream is = new FileOutputStream(localFile); //retrieveFile的第一个参数需要是 ISO-8859-1 编码,并且必须是完整路径! String fileName = remoteDir + name; ftpClient.retrieveFile(new String(fileName.getBytes("GBK"),"ISO-8859-1"), is); is.close(); //打印 long length = remoteFiles[i].getSize(); String readableLength = FileUtils.byteCountToDisplaySize(length); System.out.println(name + ":\t"+remoteFiles[i].isFile()+"\t" + readableLength); } } ftpClient.logout(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(outSteam); try { ftpClient.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * 上传 * */ public void upload(){ String srcUrl = "C:/001/菜单权限设计.doc"; String targetFileName = "菜单权限设计.doc"; try { ftpClient.connect(hostName,port); boolean b = ftpClient.login(userName, password); // 检测连接是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftpClient.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); File srcFile = new File(srcUrl); FileInputStream fis = null; fis = new FileInputStream(srcFile); // 设置上传目录 ftpClient.changeWorkingDirectory(remoteDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 上传 b = ftpClient.storeFile(targetFileName, fis); IOUtils.closeQuietly(fis); /*boolean bool = ftpClient.changeWorkingDirectory("/NC"); System.out.println("changeWorkingDirectory="+bool); bool = ftpClient.makeDirectory("/NC"); System.out.println("makeDirectory="+bool);*/ ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } /** * 测试 * */ public static void main(String[] args) { ListFtpFile listFtpfiles = new ListFtpFile(); listFtpfiles.download(); listFtpfiles.upload(); } } |
java apache.commons.net ftp 上传下载移动删除 http://www.yanjoy.com/node/39
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 |
Java代码 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; /** * @spring.bean id="apachecommonsnetftp" * @author lhb http://www.yanjoy.com * */ public class FTPCommon implements FTPInterface { private Log log = LogFactory.getLog(this.getClass()); private FTPClient ftpClient; private String username; private String password; private String url; private int port; public FTPCommon() { super(); // 从配置文件中读取初始化信息 this.ftpClient = new FTPClient(); } /** * 连接并登录FTP服务器 * */ public boolean ftpLogin() { this.ftpClient = new FTPClient(); boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig( FTPClientConfig.SYST_NT); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); this.ftpClient.setControlEncoding("UTF-8"); this.ftpClient.configure(ftpClientConfig); try { if (this.port> 0) { this.ftpClient.connect(this.url, this.port); } else { this.ftpClient.connect(this.url); } // FTP服务器连接回答 int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); return isLogin; } if(!this.ftpClient.login(this.username, this.password)){ return isLogin; } //this.ftpClient.changeWorkingDirectory(this.ftpEntity.getRemoteDir()); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // log.infoOutPut("成功登陆FTP服务器:" + this.ftpEntity.getUrl() + " 端口号:" // + this.getFtpModel().getPort() + " 目录:" // + this.ftpEntity.getRemoteDir()); isLogin = true; } catch (SocketException e) { e.printStackTrace(); // log.logPrint("连接FTP服务失败!", Constants.LOG_EXCEPTION); // log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION); } catch (IOException e) { e.printStackTrace(); // log.logPrint("登录FTP服务失败!", Constants.LOG_EXCEPTION); // log.logPrint(e.getMessage(), Constants.LOG_EXCEPTION); } System.out.println(this.ftpClient.getBufferSize()); this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(2000); return isLogin; } /** * 退出并关闭FTP连接 * */ public void close() { if (null != this.ftpClient && this.ftpClient.isConnected()) { try { boolean reuslt = this.ftpClient.logout();// 退出FTP服务器 if (reuslt) { // log.info("退出并关闭FTP服务器的连接"); } } catch (IOException e) { e.printStackTrace(); log.error("退出FTP服务器异常!"); log.error(e.getMessage()); } finally { try { this.ftpClient.disconnect();// 关闭FTP服务器的连接 } catch (IOException e) { e.printStackTrace(); log.error("关闭FTP服务器的连接异常!"); log.error(e.getMessage()); } } } } /** * 检查FTP服务器是否关闭,如果关闭接则连接登录FTP * * @return */ public boolean isOpenFTPConnection() { boolean isOpen = false; if (null == this.ftpClient) { return false; } try { // 没有连接 if (!this.ftpClient.isConnected()) { isOpen = this.ftpLogin(); } } catch (Exception e) { e.printStackTrace(); log.error("FTP服务器连接登录异常!"); log.error(e.getMessage()); isOpen = false; } return isOpen; } /** * 设置传输文件的类型[文本文件或者二进制文件] * * @param fileType--FTPClient.BINARY_FILE_TYPE,FTPClient.ASCII_FILE_TYPE */ public void setFileType(int fileType) { try { this.ftpClient.setFileType(fileType); } catch (IOException e) { e.printStackTrace(); // log.exception("设置传输文件的类型异常!"); // log.exception(e.getMessage()); } } /** * 下载文件 * * @param localFilePath * 本地文件名及路径 * @param remoteFileName * 远程文件名称 * @return */ public boolean downloadFile(String localFilePath, String remoteFileName) { BufferedOutputStream outStream = null; boolean success = false; try { outStream = new BufferedOutputStream(new FileOutputStream( localFilePath)); success = this.ftpClient.retrieveFile(remoteFileName, outStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outStream != null) { try { outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /** * 下载文件 * * @param localFilePath * 本地文件 * @param remoteFileName * 远程文件名称 * @return */ public boolean downloadFile(File localFile, String remoteFileName) { BufferedOutputStream outStream = null; FileOutputStream outStr = null; InputStream inStream = null; boolean success = false; try { outStr = new FileOutputStream(localFile); outStream = new BufferedOutputStream(outStr); //success = this.ftpClient.retrieveFile(remoteFileName, outStream); inStream = this.ftpClient.retrieveFileStream(remoteFileName); byte[] bytes = new byte[1024]; int c; while ((c = inStream.read(bytes)) != -1) { outStr.write(bytes, 0, c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != outStream) { try { outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(null != inStream){ inStream.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != outStr) { outStr.flush(); outStr.close(); } if(null != inStream){ inStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } return success; } /** * * @param outStream * @param remoteFileName * @return */ public OutputStream downloadFile(OutputStream outStream, String remoteFileName) { BufferedOutputStream bufferOutStream = null; boolean success = false; try { bufferOutStream = new BufferedOutputStream(outStream); success = this.ftpClient.retrieveFile(remoteFileName, bufferOutStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bufferOutStream; } /** * 上传文件 * * @param localFilePath * 本地文件路径及名称 * @param remoteFileName * FTP 服务器文件名称 * @return */ public boolean uploadFile(String localFilePath, String remoteFileName) { BufferedInputStream inStream = null; OutputStream osStrem = null; boolean success = false; try { inStream = new BufferedInputStream(new FileInputStream( localFilePath)); osStrem = this.ftpClient.storeFileStream(remoteFileName); byte[] bytes = new byte[1024]; int c; while ((c = inStream.read(bytes)) != -1) { osStrem.write(bytes, 0, c); } success = true; //success = this.ftpClient.storeFile(new String(remoteFileName.getBytes("UTF-8"), "ISO-8859-1"), inStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (inStream != null) { inStream.close(); } if(osStrem!=null){ osStrem.flush(); osStrem.close(); } } catch (IOException e) { e.printStackTrace(); } } return success; } /** * 上传文件 * * @param localFilePath * 本地文件 * @param remoteFileName * FTP 服务器文件名称 * @return */ public boolean uploadFile(File localFile, String remoteFileName) { BufferedInputStream inStream = null; boolean success = false; try { inStream = new BufferedInputStream(new FileInputStream(localFile)); success = this.ftpClient.storeFile(remoteFileName, inStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; } /** * 删除FTP服务器上文件 * @param remoteFileName * FTP 服务器文件名称 * @return */ public boolean delFile(String remoteFileName){ boolean success = false; try { success = this.ftpClient.deleteFile(remoteFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 删除FTP服务器上文件夹中的所有文件 * @param remoteDir * @return */ public boolean delAllFile(String remoteDir){ boolean success = false; try { this.ftpClient.changeWorkingDirectory(remoteDir); String files[] = null; files = this.ftpClient.listNames(); if(files!=null){ for(int i=0;i<files.length;i++){ success = this.ftpClient.deleteFile(files[i]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 删除FTP服务器上文件夹中的所有文件 * @param remoteDir * @return */ public boolean delAllFile(){ boolean success = false; try { String files[] = null; files = this.ftpClient.listNames(); if(files!=null){ for(int i=0;i<files.length;i++){ success = this.ftpClient.deleteFile(files[i]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 删除目录 * @param pathname * @return */ public boolean deleteDirectory(String pathname){ boolean success = false; try { success = this.ftpClient.removeDirectory(pathname); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 移动文件或重命名 * @param fromFile * @param toFile * @return */ public boolean moveFile(String fromFile, String toFile) { boolean success = false; try { success = this.ftpClient.rename(fromFile, toFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 创建文件夹 * @param dir * @return */ public boolean makeDirectory(String dir){ boolean success = false; try { success = this.ftpClient.makeDirectory(dir); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return success; } /** * 变更工作目录 * * @param remoteDir--目录路径 */ public void changeDir(String remoteDir) { try { this.ftpClient.changeWorkingDirectory(remoteDir); // log.info("变更工作目录为:" + remoteDir); } catch (IOException e) { e.printStackTrace(); log.error("变更工作目录为:" + remoteDir + "时出错!"); log.error(e.getMessage()); } } /** * 变更工作目录 * * @param remoteDir--目录路径 */ public void changeDir(String[] remoteDirs) { String dir = ""; try { for (int i = 0; i < remoteDirs.length; i++) { this.ftpClient.changeWorkingDirectory(remoteDirs[i]); dir = dir + remoteDirs[i] + "/"; } // log.info("变更工作目录为:" + dir); } catch (IOException e) { e.printStackTrace(); log.error("变更工作目录为:" + dir + "时出错!"); log.error(e.getMessage()); } } /** * 返回上级目录 * */ public void toParentDir(String[] remoteDirs) { try { for (int i = 0; i < remoteDirs.length; i++) { this.ftpClient.changeToParentDirectory(); } // log.info("返回上级目录"); } catch (IOException e) { e.printStackTrace(); log.error("返回上级目录时出错!"); log.error(e.getMessage()); } } /** * 返回上级目录 * */ public void toParentDir() { try { this.ftpClient.changeToParentDirectory(); log.info("返回上级目录"); } catch (IOException e) { e.printStackTrace(); log.error("返回上级目录时出错!"); log.error(e.getMessage()); } } /** * 获得FTP 服务器下所有的文件名列表 * * @param regex * @return */ public String[] getListFiels() { String files[] = null; try { files = this.ftpClient.listNames(); } catch (IOException e) { e.printStackTrace(); } return files; } public FTPClient getFtpClient() { return ftpClient; } public void init(String server, int port, String userName, String userPassword) { // TODO Auto-generated method stub this.url = server; this.port =port; this.username = userName; this.password = userPassword; } } |
java.net支持: Java读取远程文件[Http,ftp],并保存
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
Java代码 import java.net.*; import java.io.*; /* * Created on 2007-6-1 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ /** * @author howard * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class TestUrl { public boolean saveUrlAs(String photoUrl, String fileName) { try { URL url = new URL(photoUrl); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); DataInputStream in = new DataInputStream(connection .getInputStream()); DataOutputStream out = new DataOutputStream(new FileOutputStream( fileName)); byte[] buffer = new byte[4096]; int count = 0; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); in.close(); return true; } catch (Exception e) { System.out.println(e); return false; } } /** * 兼容HTTP和FTP协议 * @param urlString * @return */ public String getDocumentAt(String urlString) { StringBuffer document = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { document.append(line + "\n"); } reader.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } return document.toString(); } /** * * @param args */ public static void main(String[] args) { TestUrl test = new TestUrl(); String photoUrl = "http://www.zhplc.com/468x60.gif"; String fileName = photoUrl.substring(photoUrl.lastIndexOf("/")); String filePath = "c:\\"; boolean flag = test.saveUrlAs(photoUrl, filePath + fileName); System.out.println("Run ok!\n Get URL file " + flag); } } |
