首页 > 其他分享 >io流操作文件夹及文件

io流操作文件夹及文件

时间:2022-10-17 10:14:09浏览次数:56  
标签:文件 file io fileName 文件夹 File import new String

/**
     * 复制文件夹到另外的文件夹
     */
    public void process() {

        Calendar calendar = Calendar.getInstance();
        String dir = calendar.get(Calendar.YEAR) + "" + getTimeString(calendar.get(Calendar.MONTH) + "");

        String oldPath = "/img2" + dir;
        String newPath = "/img5" + dir;

        try {

            while(true){
                System.out.println("复制 " + oldPath + " 目录开始");
                long t1 = System.currentTimeMillis();

                num = 0;
                copyFolder(oldPath, newPath);

                long t2 = System.currentTimeMillis();
                System.out.println("复制目录结束,用时:" + (t2-t1) + "ms,共复制:" + num + "文件");
            }

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


    public void copyFolder(String oldPath, String newPath) {

        try {
            File mFile = new File(newPath);
            if(!mFile .exists()){
                (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()) {
                    String fileName = newPath + "/" + (temp.getName()).toString();
                    File testFile = new File(fileName);
                    if (!testFile.exists()) {
                        FileInputStream input = new FileInputStream(temp);
                        FileOutputStream output = new FileOutputStream(fileName);
                        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();
                        num++;
                    }
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }
    }

 

package com.fh.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;

/**
 * 说明:上传文件
 * 作者:FH Admin
 * 官网:fhadmin.cn
 */
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
     */
    public static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = mkdirsmy(dir,realName);
        FileUtils.copyInputStreamToFile(in, file);
        in.close();
        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;
        
    }
}



package com.fh.util;

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

import javax.servlet.http.HttpServletResponse;

/**
 * 说明:下载文件
 * 作者:FH Admin
 * 官网:fhadmin.cn
 */
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();
    } 

}

 

标签:文件,file,io,fileName,文件夹,File,import,new,String
From: https://www.cnblogs.com/xiaoyanger-study/p/16798059.html

相关文章

  • JDBC各个类详解_Connection和JDBC各个类详解_Statement
    2.Connection:数据库连接对象1.功能:1.获取执行sql的对象 StatementcreateStatement() PreparedStatementprepareStatement(Stringsql......
  • hadoop集群启动脚本文件myhadoop.sh
    #!/bin/bashif[$#-lt1]thenecho"NoArgsInput..."exit;ficase$1in"start")echo"===================启动hadoop集群==================="......
  • Collections工具类
    Collections工具类常用功能Collections是集合工具类用来集合进行操作常用方法如下1.publicstatic<T>booleanaddAll(Collectionc,Telements):往集合中添加一些元......
  • Submit report 很实用FM:RS_REFRESH_FROM_SELECTOPTIONS
    某个需求中间调用了标准的程序。带选择屏幕。写了个测试程序,玩儿的。首先写了一个取数report:然后写了个调用的report测试结果:spfli表数据:我两个report的,选择屏幕字段顺序......
  • Xcode14编译iOS11或iOS12报错dyld: Library not loaded: /usr/lib/swift/libswiftCore
    在更新Xcode14之后发现编译项目在iOS12.5以上的系统都正常,但是在跑iOS12.5以下的系统,例如iOS11,和iOS12.1之类的系统会报错,报错如下:dyld:Librarynotloaded:/usr/lib/sw......
  • rsync同步SQLite3文件API返回旧数据
    问题描述EFCorecannotgetnewvalueindocker,ifusersyncreplacesqlitefile基于.NET6开发一个查询SQLite的API,使用Docker进行部署,通过挂载的方式来访问数据库文......
  • Vicinity Vision Transformer概述
    0.前言相关资料:arxivgithub论文解读论文基本信息:发表时间:arxiv2022(2022.6.21)1.针对的问题视觉transformer计算复杂度和内存占用都是二次......
  • Collection集合
    集合的概述集合:集合是java中提供一种容器可以用来存储多个数据数组的长度是固定的集合的长度是可变的数组中存储是同一类型的元素可以存储基本数据值集合存储的都是......
  • JDBC各个类详解-DriverManager-获取数据库连接和JDBC各个类详解-Connection
    JDBC各个类详解-DriverManager-获取数据库连接获取数据库连接:方法:staticConnectiongetConnection(String url,String user,String password)参数:......
  • skyler实战渗透笔记(十一)—Kioptrix-1
    skyler实战渗透笔记:笔记是为了记录实战渗透学习过程,分享渗透过程思路与方法。请注意:对于所有笔记中复现的终端或服务器,都是自行搭建环境或已获授权渗透的。使用的技术仅......