美文网首页hello,world!
(JAVA)文件读写辅助类

(JAVA)文件读写辅助类

作者: 霙愔 | 来源:发表于2016-10-14 16:34 被阅读59次

import java.io.BufferedInputStream;
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.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 文件读写辅助类
 *
 * @since 2012-03-17
 *
 */
public class FileUtils {
 /**
  * 复制单个文件
  *
  * @param oldFile
  *            :File
  * @param newPath
  *            :String 文件路径
  */
 public static void copyFile(File oldFile, String newPath) {

  Long starttime = System.currentTimeMillis();

  InputStream inStream = null;
  FileOutputStream fout = null;

  try {
   int bytesum = 0;
   int byteread = 0;

   if (oldFile.exists()) { // 文件存在时
    inStream = new FileInputStream(oldFile); // 读入原文件
    
    File file = new File(newPath.substring(0, newPath.lastIndexOf("\\")));
    //文件不存在时,建文件
    if(!file.exists()) {
     file.mkdirs();
    }
    
    fout = new FileOutputStream(newPath);

    byte[] buffer = new byte[1024];

    while ((byteread = inStream.read(buffer)) != -1) {
     bytesum += byteread; // 字节数 文件大小
     fout.write(buffer, 0, byteread);
    }

    fout.flush();

   }
  } catch (Exception e) {
   System.out.println("复制文件【" + oldFile.getAbsolutePath() + "】时出错!");
   e.printStackTrace();

  } finally {
   try {
    // 关闭输入流
    if (inStream != null) {
     inStream.close();
    }

    // 关闭输出流
    if (fout != null) {
     fout.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  Long endtime = System.currentTimeMillis();
  System.out.println("复制【" + oldFile.getAbsolutePath() + " 】用时【"
    + (endtime - starttime) + "】毫秒!");
 }

 /**
  * 复制单个文件
  *
  * @param inStream
  *            :輸入流
  * @param newPath
  *            :String 文件路径
  */
 public static void copyFile(InputStream inStream, String newPath) {

  FileOutputStream fout = null;

  try {
   int bytesum = 0;
   int byteread = 0;
   File file = new File(newPath.substring(0, newPath.lastIndexOf("\\")));
   
   //文件不存在时,建文件
   if(!file.exists()) {
    file.mkdirs();
   }
   
   fout = new FileOutputStream(newPath);

   byte[] buffer = new byte[1024];

   while ((byteread = inStream.read(buffer)) != -1) {
    bytesum += byteread; // 字节数 文件大小
    fout.write(buffer, 0, byteread);
   }

   fout.flush();

  } catch (Exception e) {
   e.printStackTrace();

  } finally {
   try {
    // 关闭输入流
    if (inStream != null) {
     inStream.close();
    }

    // 关闭输出流
    if (fout != null) {
     fout.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 /**
  * 复制文件夹
  *
  * @param oldPath
  *            :String 文件路径
  * @param newPath
  *            :String 文件路径
  */
 public static void copyFolder(String oldPath, String newPath) {

  try {
   (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
   File oldfiles = new File(oldPath);
   String[] file = oldfiles.list();// 循环时用于存放临时的文件列表
   File tempfile = null;// 存放临时文件

   for (int i = 0; i < file.length; i++) {
    // 循环拿到文件夹下的每个文件
    if (oldPath.endsWith(File.separator)) {
     tempfile = new File(oldPath + file[i]);
    } else {
     tempfile = new File(oldPath + File.separator + file[i]);
    }

    // 是文件,就直接拷文件
    if (tempfile.isFile()) {
     copyFile(tempfile, newPath + "/"
       + (tempfile.getName()).toString());
    }

    // 是文件夾,继续循环拷文件夹
    if (tempfile.isDirectory()) {
     copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
    }
   }
  } catch (Exception e) {
   System.out.println("复制文件夹【" + oldPath + "】时出错!");
   e.printStackTrace();

  }

 }
 
 /**
  * 下载项目里面的文件
  *
  * @param request
  * @param response
  */
 public static void doDownFile(HttpServletRequest request,
   HttpServletResponse response, String filePath, String fileRealName) {
  InputStream ins = null;
  ServletOutputStream toClient = null;
  File file = null;

  // 从页面读取文件路径
  if (filePath != null) {
   try {
    file = new File(request.getRealPath("/") + filePath);
    if (file.exists()) {
     ins = new FileInputStream(file);
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
    System.out.println("文件不存在!");
   }

   response.reset();

   // 得到保存的文件名
   String filename = null;
   try {
    /*filename = new String(filePath.substring(
      filePath.lastIndexOf("\\") + 1).getBytes("GBK"),
      "ISO-8859-1");*/
    filename = new String(fileRealName.getBytes("GBK"),"ISO-8859-1");
    
    response.setHeader("Content-disposition",
      "attachment;filename=" + filename);

    response.setContentType("application/x-msdownload");

    response.setContentType("application/octet-stream;charset=GBK");

    // 解决在弹出文件下载框不能打开文件的问题
    response.addHeader("Content-Disposition",
      "attachment; filename="
        + URLEncoder.encode(filename, "GBK"));

   } catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
    System.out.println("文件名转码时出错!");
   }

   BufferedInputStream bis = new BufferedInputStream(ins);
   try {
    // 得到客户端输出流
    toClient = response.getOutputStream();

    byte[] b = new byte[8192];
    int len = 0;

    while ((len = bis.read(b)) != -1) {
     // 向客户端写文件
     toClient.write(b, 0, len);
    }
   } catch (IOException e) {
    e.printStackTrace();
    System.out.println("文件读取时出错!");
   } finally {
    // 关闭流
    try {
     if (bis != null) {
      bis.close();
     }
     if (ins != null) {
      ins.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 
 
 /**
  * 删除文件夹辅助方法
  *
  * @param filePath
  * @return
  */
 public static void deleteFile(String filePath) {
  // boolean flag = false;
  File file = new File(filePath);
  // 判断目录或文件是否存在
  if (!file.exists()) { // 不存在返回 false
   // return flag;
  } else {
   // 判断是否为文件
   if (file.isFile()) { // 为文件时调用删除文件方法
    file.delete();
   } else { // 为目录时调用删除目录方法
    File[] files = file.listFiles();
    for (int i = 0; i < files.length; i++) {
     // 刪除子文件夾
     deleteFile(files[i].getAbsolutePath());
    }
   }
  }
 }
}

本文已在版权印备案,如需转载请访问版权印。86818759

相关文章

  • (JAVA)文件读写辅助类

    import java.io.BufferedInputStream;import java.io.File;im...

  • Java(八)--文件I/O

    File类不包含读写文件内容的方法。封装了文件或者路径的属性。不包括创建文件和读写 import java.io....

  • Scala编程基础29:Scala读写操作

    Scala进行文件读写操作,都是直接调用的Java中的IO类:java.io.File。 1.Scala写文件 下...

  • Java读写资源文件类Properties

    Java中读写资源文件最重要的类是Properties 1) 资源文件要求如下: properties文件是一个文...

  • Java IO流 个人总结

    Java流类图结构 描述: Java的核心库java.io提供了全面的IO接口。包括:文件读写、标准设备输出等。J...

  • Java File 文件操作

    java.io包里的类: InputStream/OutputStream : 以字节为单位读写文件内容,一次读/...

  • java7新特性8-异步通道

    异步IO通道 Java7之前,要异步实现对大文件的读写,借助java.util.concurrent中的相关类库也...

  • Java基础知识学习——流

    一、JAVA流式输入/输出原理 流是用来读写数据的,java有一个类叫File,它封装的是文件的文件名,只是内存里...

  • 001.流 上卷 概念

    1.JAVA流式输入/输出原理 流是用来读写数据的,Java有一个类叫File,它封装的是文件的文件名,只是内存里...

  • Javassist 指南1

    1、读写字节码 Javassist 是一个能处理 Java字节码 的类库,Java字节码存储在class文件中,每...

网友评论

本文标题:(JAVA)文件读写辅助类

本文链接:https://www.haomeiwen.com/subject/bdtnyttx.html