java 文件上传下载

一、下载网上资源到本地
//资源url 
String urlpath = "https://img6.bdstatic.com/img/image/smallpic/1.jpg";  
URL url = new URL(urlpath);  
//下载资源  
DataInputStream dataInputStream = new DataInputStream(url.openStream());  
//当前目录
FileOutputStream fileOutputStream = new FileOutputStream(new File("1.jpg"));  




二、远程共享目录操作
1、需要下载对应的jcifs-1.3.18.jar
2、涉及的主要类是  SmbFile(远程文件操作类) ,还有就是进行登录验证,验证对应的远程目录的合法性的操作
3、上传
a:连接远程
InetAddress ip = InetAddress.getByName("10.20.12.75"); 
        UniAddress address = new UniAddress(ip);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("10.20.12.75", "xu_qingqing@hoperun.com", "Xuqq123");//远程共享目录所在的IP,用户名,密码
        SmbSession.logon(address,auth); 
b:找到存放文件的路径
SmbFile remoteFile = new SmbFile("smb://pc11130/share2/_upfile/201804/_books/Page60_books_002", auth);
        remoteFile.connect();    
c:写文件
OutputStream  out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
out.write(toByteArray(localFile));

//可以在处理大文件时,提升性能
public static byte[] toByteArray(File file) throws IOException {
FileChannel fc = new RandomAccessFile(file, "r").getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
                    fc.size()).load();
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
}

4、下载
SmbFile remoteFile = new SmbFile(removeDir + _fileName, auth);
File localFile = new File(localDir + fileName);
InputStream in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
        OutputStream out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }


三、FTP
FTPClient ftp = new FTPClient();  
ftp.connect(host, port);// 连接FTP服务器  
ftp.login(username, password);// 登录  
int reply = ftp.getReplyCode();  
if (!FTPReply.isPositiveCompletion(reply)) {  //登录失败
                ftp.disconnect();  
                return result;  
            }  
//设置上传文件的类型为二进制类型  
    ftp.setFileType(FTP.BINARY_FILE_TYPE);  
ftp.setControlEncoding("utf-8");
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
ftp.storeFile(filename, input);//filename 上传到FTP服务器上的文件名,input 输入流
ftp.retrieveFile(filename, is); //fileName 要下载的文件名,is 输出流
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值