zoukankan      html  css  js  c++  java
  • Java 实现文件上传、下载、打包、文件copy、文件夹copy。

    文件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("
    "));
                    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("
    ",pos) + 1; 
                    pos = file.indexOf("
    ",pos) + 1; 
                    pos = file.indexOf("
    ",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();
                }
            }
            
        }
    }
  • 相关阅读:
    【C++】资源管理
    【Shell脚本】逐行处理文本文件
    【算法题】rand5()产生rand7()
    【Shell脚本】字符串处理
    Apple iOS产品硬件参数. 不及格的程序员
    与iPhone的差距! 不及格的程序员
    iPhone游戏 Mr.Karoshi"过劳死"通关. 不及格的程序员
    XCode V4 发布了, 苹果的却是个变态. 不及格的程序员
    何时readonly 字段不是 readonly 的?结果出呼你想象!!! 不及格的程序员
    object file format unrecognized, invalid, or unsuitable Command 不及格的程序员
  • 原文地址:https://www.cnblogs.com/qisel/p/3877709.html
Copyright © 2011-2022 走看看