文件and文件夹copy

package org.test;

import java.io.*;

public class FileCopy {

    /**
* 复制单个文件
*
* @param oldPath
* String 原文件路径 如:D:\\bbbb\\ssss.txt
* @param newPath
* String 复制后路径 如:D:\\bbbb\\aa\\ssss.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPath); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
} /**
* 复制整个文件夹内容
*
* @param oldPath
* String 原文件路径 如:D:\\bbbb
* @param newPath
* String 复制后路径 如:E:\\bbbb
* @return boolean
*/
public void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
} public static void main(String args[]) {
FileCopy bp = new FileCopy();
bp.copyFile("D:\\bbbb\\ssss.txt","D:\\bbbb\\aa\\ssss.txt" );
bp.copyFolder("D:\\bbbb", "E:\\bbbb");
}
}

文件下载

package org.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*; public class FileDownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.downLoad(req, resp);
} public void downLoad(HttpServletRequest req, HttpServletResponse resp)
throws IOException { String fileTrueName = req.getParameter("fileName");
resp.setContentType("application/x-msdownload; charset=utf-8");
resp.setHeader("Content-disposition", "attachment;filename=\""
+ fileTrueName + "\""); byte[] buffered = new byte[1024]; BufferedInputStream input = new BufferedInputStream(
new FileInputStream("D:/" + fileTrueName));
DataOutputStream output = new DataOutputStream(resp.getOutputStream()); while (input.read(buffered, 0, buffered.length) != -1) {
output.write(buffered, 0, buffered.length);
} input.close();
output.close();
} }

对文件夹进行打包

package org.test;

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.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
* 将文件打包成ZIP压缩文件
* @author LanP
* @since 2012-3-1 15:47
*/
public final class FileToZip { private FileToZip() { } /**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的ZIP文件,并存放到zipFilePath。
* @param sourceFilePath 待压缩的文件路径
* @param zipFilePath 压缩后存放路径
* @param fileName 压缩后文件的名称
* @return flag
*/
public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null; if(sourceFile.exists() == false) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 不存在. <<<<<<");
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if(zipFile.exists()) {
System.out.println(">>>>>> " + zipFilePath + " 目录下存在名字为:" + fileName + ".zip" + " 打包文件. <<<<<<");
} else {
File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length < 1) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 里面不存在文件,无需压缩. <<<<<<");
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024*10];
for(int i=0;i<sourceFiles.length;i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis,1024*10);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1) {
zos.write(bufs, 0, read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if(null != bis) bis.close();
if(null != zos) zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
} return flag;
} /**
* 将文件打包成ZIP压缩文件,main方法测试
* @param args
*/
public static void main(String[] args) {
String sourceFilePath = "D:\\aaaa";
String zipFilePath = "D:\\aaaa";
String fileName = "aaaa";
boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
if(flag) {
System.out.println(">>>>>> 文件打包成功. <<<<<<");
} else {
System.out.println(">>>>>> 文件打包失败. <<<<<<");
}
}
}

下载

package org.test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String oper = request.getParameter("oper"); if ("upDownLoad".equals(oper)) {
this.upDownLoad(request, response);
}
} public void upDownLoad(HttpServletRequest request,HttpServletResponse response){ boolean flag = false;
String successMessage = "Upload file successed."; String fileName = null;
DataInputStream in = null;
FileOutputStream fileOut = null; /** 取得客户端的传递类型 */
String contentType = request.getContentType();
byte dataBytes[] = null ;
try {
/** 确认数据类型是 multipart/form-data */
if (contentType != null
&& contentType.indexOf("multipart/form-data") != -1) {
/** 取得上传文件流的字节长度 */
int fileSize = request.getContentLength(); /** 可以判断文件上传上线
if (fileSize > MAX_SIZE) {
successMessage = "Sorry, file is too large to upload.";
return;
} */ /** 读入上传的数据 */
in = new DataInputStream(request.getInputStream()); /** 保存上传文件的数据 */
int byteRead = 0;
int totalBytesRead = 0;
dataBytes = new byte[fileSize]; /** 上传的数据保存在byte数组 */
while(totalBytesRead < fileSize){
byteRead = in.read(dataBytes, totalBytesRead, fileSize);
totalBytesRead += byteRead;
} int i = dataBytes.length;
/** 根据byte数组创建字符串 */
String file = new String(dataBytes,"UTF-8");
i = file.length();
/** 取得上传的数据的文件名 */ String upFileName = file.substring(file.indexOf("filename=\"") + 10);
upFileName = upFileName.substring(0, upFileName.indexOf("\n"));
upFileName = upFileName.substring(upFileName.lastIndexOf("\\") + 1, upFileName.indexOf("\"")); /** 取得数据的分隔字符串 */
String boundary = contentType.substring(contentType.lastIndexOf("boundary=") + 9, contentType.length());
/** 创建保存路径的文件名 */
fileName = upFileName; int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos)-4; /** 取得文件数据的开始的位置 */
int startPos = file.substring(0, pos).length(); /** 取得文件数据的结束的位置 */
int endPos = file.substring(boundaryLocation).length(); /** 创建文件的写出类 */
// fileOut = new FileOutputStream(this.getServletContext().getRealPath("/image")+"/"+fileName);
fileOut = new FileOutputStream("D:"+"/"+fileName);
/** 保存文件的数据 */
fileOut.write(dataBytes, startPos, (fileSize - endPos - startPos)); }else{
successMessage = "Data type is not multipart/form-data.";
} } catch (Exception e) {
successMessage = e.getMessage(); } finally {
try {
//close open file
in.close();
if(flag){
response.getOutputStream().write(("<a href=\"download?fileName="+fileName+"\" ><img src=\"image/"+fileName+"\"/></a>").getBytes());
}
response.getOutputStream().write(successMessage.getBytes());
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
} }
}

Java 实现文件上传、下载、打包、文件copy、文件夹copy。的更多相关文章

  1. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  2. java中的文件上传下载

    java中文件上传下载原理 学习内容 文件上传下载原理 底层代码实现文件上传下载 SmartUpload组件 Struts2实现文件上传下载 富文本编辑器文件上传下载 扩展及延伸 学习本门课程需要掌握 ...

  3. JavaWeb 文件上传下载

    1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端,从服务器端下载文件到本地的过程.例如目前网站需要上传头像.上传下载图片或网盘等功能都是利用文件上传下 ...

  4. javaEE(14)_文件上传下载

    一.文件上传概述 1.实现web开发中的文件上传功能,需完成如下二步操作: •在web页面中添加上传输入项•在servlet中读取上传文件的数据,并保存到本地硬盘中. 2.如何在web页面中添加上传输 ...

  5. 转载:JavaWeb 文件上传下载

    转自:https://www.cnblogs.com/aaron911/p/7797877.html 1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端 ...

  6. 阿里云负载均衡SLB的文件上传下载问题解决

    Nfs同步文件夹配置 问题描述 : javaweb应用部署到云服务器上时,当服务器配置了SLB负载均衡的时候,多台服务器就会造成文件上传下载获取不到文件的错误, 解决办法有:1.hdfs  2.搭建f ...

  7. Java 客户端操作 FastDFS 实现文件上传下载替换删除

    FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...

  8. JAVA Web 之 struts2文件上传下载演示(二)(转)

    JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...

  9. JAVA Web 之 struts2文件上传下载演示(一)(转)

    JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...

  10. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

随机推荐

  1. 自然语言26_perplexity信息

    http://www.ithao123.cn/content-296918.html 首页 > 技术 > 编程 > Python > Python 文本挖掘:简单的自然语言统计 ...

  2. [NHibernate]Nullables

    系列文章 [Nhibernate]体系结构 [NHibernate]ISessionFactory配置 [NHibernate]持久化类(Persistent Classes) [NHibernate ...

  3. mysql安装使用笔记

    mysql2008年被sun公司10亿美元收购, 后sun被oracle收购. widenius : 维德纽斯重新写的mysql的分支 mariaDB. 白发程序员, 是由 瑞典mysql AB公司开 ...

  4. 你想的到想不到的 javascript 应用小技巧方法

    javascript 在前端应用体验小技巧继续积累. 事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElemen ...

  5. 【译文】Java Logging

    本文讲Java内置的java.util.logging软件包中的 api.主要解释怎样使用该api添加logging到你的application中,怎样加配置它等.但是本文不谈你应该把什么东西写到日志 ...

  6. R语言:规划求解优化ROI

    今天看到一篇文章介绍如何用excel建模对ROI 进行规划求解. 蓝鲸的网站分析笔记 成本 Cost 每次点击费用 CPC 点击量 \[clickRate = \frac{cost}{CPC}\] 转 ...

  7. 【强烈推荐】如何给TortoiseGit 配置密钥?

    TortoiseGit 使用扩展名为ppk的密钥,而不是ssh-keygen生成的rsa密钥.也就是说使用 ssh-keygen -C "username@email.com" - ...

  8. H5案例分享:使用JS判断客户端、浏览器、操作系统类型

    使用JS判断客户端.浏览器.操作系统类型 一.JS判断客户端类型 JS判断客户端是否是iOS或者Android手机移动端 通过判断浏览器的userAgent,用正则来判断手机是否是ios和Androi ...

  9. 引用项目外dll时不显示注释的解决方案

    在引用项目外的dll时,显示类库中的注释可按以下步骤: 方法或变量用summary添加注释,如:         /// <summary>发送post请求         /// < ...

  10. Lua手动编译姿势

    LUA-5.3.3.tar.gz Lua源码+链接2016年5月30日更新 手动编译姿势: 已经装有VS2010 使用VS自带的 cl.exe以及 VS命令簿 打开文件地址 运行自己的bat文件 my ...