• 文件操作


    1.DelAllFile

    package com.flc.util;

    import java.io.File;

    public class DelAllFile {

    public static void main(String args[]) {
    delFolder("e:/e/a"); //只删除e下面a及a下面所有文件和文件夹,e不会被删掉
    //delFolder("D:/WEBSerser/apache-tomcat-8.0.15/me-webapps/UIMYSQL/WEB-INF/classes/../../admin00/ftl/code");
    //delFolder("D:\WEBSerser\apache-tomcat-8.0.15\me-webapps\UIMYSQL\admin00\ftl\code");
    //delFolder("D:/WEBSerser/apache-tomcat-8.0.15/me-webapps/UIMYSQL/WEB-INF/classes/../../admin00/ftl/code");
    System.out.println("deleted");
    }

    /**
    * @param folderPath 文件路径 (只删除此路径的最末路径下所有文件和文件夹)
    */
    public static void delFolder(String folderPath) {
    try {
    delAllFile(folderPath); // 删除完里面所有内容
    String filePath = folderPath;
    filePath = filePath.toString();
    java.io.File myFilePath = new java.io.File(filePath);
    myFilePath.delete(); // 删除空文件夹
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * 删除指定文件夹下所有文件
    * @param path 文件夹完整绝对路径
    */
    public static boolean delAllFile(String path) {
    boolean flag = false;
    File file = new File(path);
    if (!file.exists()) {
    return flag;
    }
    if (!file.isDirectory()) {
    return flag;
    }
    String[] tempList = file.list();
    File temp = null;
    for (int i = 0; i < tempList.length; i++) {
    if (path.endsWith(File.separator)) {
    temp = new File(path + tempList[i]);
    } else {
    temp = new File(path + File.separator + tempList[i]);
    }
    if (temp.isFile()) {
    temp.delete();
    }
    if (temp.isDirectory()) {
    delAllFile(path + "/" + tempList[i]); // 先删除文件夹里面的文件
    delFolder(path + "/" + tempList[i]); // 再删除空文件夹
    flag = true;
    }
    }
    return flag;
    }
    }

    2.FileDownload 文件下载

    package com.flc.util;

    import java.io.BufferedOutputStream;
    import java.io.OutputStream;
    import java.net.URLEncoder;

    import javax.servlet.http.HttpServletResponse;

    public class FileDownload {

    /**
    * @param response
    * @param filePath //文件完整路径(包括文件名和扩展名)
    * @param fileName //下载后看到的文件名
    * @return 文件名
    */
    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{

    byte[] data = FileUtil.toByteArray2(filePath);
    fileName = URLEncoder.encode(fileName, "UTF-8");
    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename="" + fileName + """);
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream;charset=UTF-8");
    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    outputStream.write(data);
    outputStream.flush();
    outputStream.close();
    response.flushBuffer();

    }

    }

    3.文件上传FileUpload

    package com.flc.util;

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;

    import org.apache.commons.io.FileUtils;
    import org.springframework.web.multipart.MultipartFile;


    public class FileUpload {

    /**上传文件
    * @param file //文件对象
    * @param filePath //上传路径
    * @param fileName //文件名
    * @return 文件名
    */
    public static String fileUp(MultipartFile file, String filePath, String fileName){
    String extName = ""; // 扩展名格式:
    try {
    if (file.getOriginalFilename().lastIndexOf(".") >= 0){
    extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    }
    copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
    } catch (IOException e) {
    System.out.println(e);
    }
    return fileName+extName;
    }

    /**
    * 写文件到当前目录的upload目录中
    * @param in
    * @param fileName
    * @throws IOException
    */
    private static String copyFile(InputStream in, String dir, String realName)
    throws IOException {
    File file = mkdirsmy(dir,realName);
    FileUtils.copyInputStreamToFile(in, file);
    return realName;
    }


    /**判断路径是否存在,否:创建此路径
    * @param dir 文件路径
    * @param realName 文件名
    * @throws IOException
    */
    public static File mkdirsmy(String dir, String realName) throws IOException{
    File file = new File(dir, realName);
    if (!file.exists()) {
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    return file;
    }


    /**下载网络图片上传到服务器上
    * @param httpUrl 图片网络地址
    * @param filePath 图片保存路径
    * @param myFileName 图片文件名(null时用网络图片原名)
    * @return 返回图片名称
    */
    public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {

    URL url; //定义URL对象url
    BufferedInputStream in; //定义输入字节缓冲流对象in
    FileOutputStream file; //定义文件输出流对象file
    try {
    String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
    url = new URL(httpUrl); //初始化url对象
    in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流
    //file = new FileOutputStream(new File(filePath +"\"+ fileName));
    file = new FileOutputStream(mkdirsmy(filePath,fileName));
    int t;
    while ((t = in.read()) != -1) {
    file.write(t);
    }
    file.close();
    in.close();
    return fileName;
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return null;

    }
    }

    4.文件压缩 FileZip

    package com.flc.util;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    public class FileZip {

    /**
    * @param inputFileName 你要压缩的文件夹(整个完整路径)
    * @param zipFileName 压缩后的文件(整个完整路径)
    * @throws Exception
    */
    public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
    zip(zipFileName, new File(inputFileName));
    return true;
    }

    private static void zip(String zipFileName, File inputFile) throws Exception {
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
    zip(out, inputFile, "");
    out.flush();
    out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
    if (f.isDirectory()) {
    File[] fl = f.listFiles();
    out.putNextEntry(new ZipEntry(base + "/"));
    base = base.length() == 0 ? "" : base + "/";
    for (int i = 0; i < fl.length; i++) {
    zip(out, fl[i], base + fl[i].getName());
    }
    } else {
    out.putNextEntry(new ZipEntry(base));
    FileInputStream in = new FileInputStream(f);
    int b;
    //System.out.println(base);
    while ((b = in.read()) != -1) {
    out.write(b);
    }
    in.close();
    }
    }

    public static void main(String [] temp){
    try {
    zip("E:\ftl","E:\test.zip");//你要压缩的文件夹 和 压缩后的文件
    }catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    }

    //=====================文件压缩=========================
    /*//把文件压缩成zip
    File zipFile = new File("E:/demo.zip");
    //定义输入文件流
    InputStream input = new FileInputStream(file);
    //定义压缩输出流
    ZipOutputStream zipOut = null;
    //实例化压缩输出流,并制定压缩文件的输出路径 就是E盘下,名字叫 demo.zip
    zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
    zipOut.putNextEntry(new ZipEntry(file.getName()));
    //设置注释
    zipOut.setComment("www.demo.com");
    int temp = 0;
    while((temp = input.read()) != -1) {
    zipOut.write(temp);
    }
    input.close();
    zipOut.close();*/
    //==============================================

    5.文件处理

    package com.flc.util;

    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    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.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;

    public class FileUtil {


    /**获取文件大小 返回 KB 保留3位小数 没有文件时返回0
    * @param filepath 文件完整路径,包括文件名
    * @return
    */
    public static Double getFilesize(String filepath){
    File backupath = new File(filepath);
    return Double.valueOf(backupath.length())/1000.000;
    }

    /**
    * 创建目录
    * @param destDirName目标目录名
    * @return
    */
    public static Boolean createDir(String destDirName) {
    File dir = new File(destDirName);
    if(!dir.getParentFile().exists()){ //判断有没有父路径,就是判断文件整个路径是否存在
    return dir.getParentFile().mkdirs(); //不存在就全部创建
    }
    return false;
    }

    /**
    * 删除文件
    * @param filePathAndName
    * String 文件路径及名称 如c:/fqf.txt
    * @param fileContent
    * String
    * @return boolean
    */
    public static void delFile(String filePathAndName) {
    try {
    String filePath = filePathAndName;
    filePath = filePath.toString();
    java.io.File myDelFile = new java.io.File(filePath);
    myDelFile.delete();
    } catch (Exception e) {
    System.out.println("删除文件操作出错");
    e.printStackTrace();
    }
    }

    /**
    * 读取到字节数组0
    * @param filePath //路径
    * @throws IOException
    */
    public static byte[] getContent(String filePath) throws IOException {
    File file = new File(filePath);
    long fileSize = file.length();
    if (fileSize > Integer.MAX_VALUE) {
    System.out.println("file too big...");
    return null;
    }
    FileInputStream fi = new FileInputStream(file);
    byte[] buffer = new byte[(int) fileSize];
    int offset = 0;
    int numRead = 0;
    while (offset < buffer.length
    && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
    offset += numRead;
    }
    // 确保所有数据均被读取
    if (offset != buffer.length) {
    throw new IOException("Could not completely read file " + file.getName());
    }
    fi.close();
    return buffer;
    }

    /**
    * 读取到字节数组1
    *
    * @param filePath
    * @return
    * @throws IOException
    */
    public static byte[] toByteArray(String filePath) throws IOException {

    File f = new File(filePath);
    if (!f.exists()) {
    throw new FileNotFoundException(filePath);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
    BufferedInputStream in = null;
    try {
    in = new BufferedInputStream(new FileInputStream(f));
    int buf_size = 1024;
    byte[] buffer = new byte[buf_size];
    int len = 0;
    while (-1 != (len = in.read(buffer, 0, buf_size))) {
    bos.write(buffer, 0, len);
    }
    return bos.toByteArray();
    } catch (IOException e) {
    e.printStackTrace();
    throw e;
    } finally {
    try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    bos.close();
    }
    }

    /**
    * 读取到字节数组2
    *
    * @param filePath
    * @return
    * @throws IOException
    */
    public static byte[] toByteArray2(String filePath) throws IOException {
    File f = new File(filePath);
    if (!f.exists()) {
    throw new FileNotFoundException(filePath);
    }
    FileChannel channel = null;
    FileInputStream fs = null;
    try {
    fs = new FileInputStream(f);
    channel = fs.getChannel();
    ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
    while ((channel.read(byteBuffer)) > 0) {
    // do nothing
    // System.out.println("reading");
    }
    return byteBuffer.array();
    } catch (IOException e) {
    e.printStackTrace();
    throw e;
    } finally {
    try {
    channel.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    fs.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    /**
    * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
    *
    * @param filename
    * @return
    * @throws IOException
    */
    public static byte[] toByteArray3(String filePath) throws IOException {

    FileChannel fc = null;
    RandomAccessFile rf = null;
    try {
    rf = new RandomAccessFile(filePath, "r");
    fc = rf.getChannel();
    MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
    fc.size()).load();
    //System.out.println(byteBuffer.isLoaded());
    byte[] result = new byte[(int) fc.size()];
    if (byteBuffer.remaining() > 0) {
    // System.out.println("remain");
    byteBuffer.get(result, 0, byteBuffer.remaining());
    }
    return result;
    } catch (IOException e) {
    e.printStackTrace();
    throw e;
    } finally {
    try {
    rf.close();
    fc.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    /**
    * 保存文件流到文件
    * @param fileName
    * @param in
    * @throws IOException
    */
    public static void saveToFile(String fileName, InputStream in) throws IOException {
    FileOutputStream fos = null;
    BufferedInputStream bis = null;

    //存在则删除
    File _file = new File(fileName);
    if(_file.exists()){
    _file.delete();
    }

    int BUFFER_SIZE = 1024;
    byte[] buf = new byte[BUFFER_SIZE];
    int size = 0;
    bis = new BufferedInputStream(in);
    fos = new FileOutputStream(fileName);

    //保存文件
    while ((size = bis.read(buf)) != -1)
    fos.write(buf, 0, size);
    fos.close();
    bis.close();
    }

    }

  • 相关阅读:
    Django rest_framework之序列化(serializers)
    异常处理
    Django之ModelForm通过ajax用户登录验证
    Django之ModelForm用户登录注册
    Django之Model操作
    Jenkins+Maven+SVN+Nexus 搭建持续集成环境
    nginx rewrite域名跳转访问XML接口
    python自动发布应用脚本
    Django基础
    Web安全概述
  • 原文地址:https://www.cnblogs.com/Sora-L/p/9003317.html
Copyright © 2020-2023  润新知