java文件操作

原创
2018/01/03 00:08
阅读数 57

文件操作

Java文件类以抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等。 File对象代表磁盘中实际存在的文件和目录。

下面是File对象常用的方法

  • File file = new File("file path") //获取文件对象
  • file.exists() 文件是否存在
  • file.isDirectory() 判断文件是否为目录
  • file.listFiles() 获取目录下的所有File的数组
  • file.getName() 获取文件或目录名称
  • file.isDirectory() File是否为目录
  • file.getPath() 获取File的路径
  • file.isFile() 判断File是否为标准文件
  • file.lastModified() File的最后修改时间
  • file.delete() 删除File
  • file.list() 返回文件或目录名称的数组
  • file.listFiles() 返回
  • file.mkdir() 创建目录
  • file.mkdirs() 递归的创建目录
  • file.renameTo(File dest) 重命名文件或目录
  • file.compareTo(File pathname) 按字母顺序比较两个路径名

例子

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/file")
public class FileController {

    //创建文件
    @GetMapping("/touch")
    public JData create(@RequestParam(value = "path") String path)throws Exception{
        File file = new File(path);
        Boolean isCreate = file.createNewFile();
        return new JData(1,"ok",isCreate);
    }

    //创建目录
    @GetMapping("/mkdir")
    public JData mkdir(@RequestParam(value = "path") String path){
        File file = new File(path);
        Boolean isCreate = file.mkdir();
        return new JData(1,"ok",isCreate);
    }

    //递归创建目录
    @GetMapping("/mkdirs")
    public JData mkdirs(@RequestParam(value = "path") String path){
        File file = new File(path);
        Boolean isCreate = file.mkdirs();
        return new JData(1,"ok",isCreate);
    }

    // 删除文件或目录
    @GetMapping("/rm")
    public JData rm(@RequestParam(value = "path") String path){
        File file = new File(path);
        if(!file.exists()){
            return new JData(0,"文件不存在",0);
        }
        if(!file.delete()){
            return new JData(0,"删除失败",0);
        }
        return new JData(1,"ok",1);
    }

    //递归删除目录及文件
    @GetMapping("/rmAll")
    public JData rms(@RequestParam(value = "path")String path){
        File file = new File(path);
        if(!file.exists()){
            return new JData(0,"文件不存在",0);
        }
        deleteFolder(file);
        return new JData(1,"删除成功",1);
    }

    //递归删除目录及文件
    private void deleteFolder(File folder){
        File[] files = folder.listFiles();
        if(files!=null){
            for(File f:files){
                if(f.isDirectory()){
                    deleteFolder(f);
                }else{
                    f.delete();
                }
            }
        }
        folder.delete();
    }

    //修改文件或目录名
    @GetMapping("/rename")
    public JData rename(@RequestParam(value = "target")String target,@RequestParam(value = "dest")String dest){
        File file = new File(target);
        File destFile = new File(dest);
        Boolean isRename = file.renameTo(destFile);
        return new JData(1,"ok",isRename);
    }

    //移动文件
    @GetMapping("/mv")
    public JData mv(@RequestParam(value = "target") String target,@RequestParam(value = "dest")String dest)throws Exception{
        File targetFile = new File(target);
        File destFile = new File(dest);

        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(targetFile);
        FileOutputStream out=new FileOutputStream(destFile);

        byte[] buffer=new byte[length];
        while(true) {
            int ins = in.read(buffer);
            if (ins == -1) {
                in.close();
                out.flush();
                out.close();
                targetFile.delete();
                return new JData(1, "ok", new Date().getTime() - time);
            } else {
                out.write(buffer, 0, ins);
            }
        }
    }

    //拷贝目录及文件
    @GetMapping("/copy")
    public JData copy(@RequestParam(value = "target")String target,@RequestParam("dest")String dest)throws Exception{
        File targetFile = new File(target);
        File destFile = new File(dest);
        if(!targetFile.exists() || !destFile.exists()){
            return new JData(0,"目标目录或源目录为空",0);
        }

        String rootPath = targetFile.getName();
        recursiveCopy(target,dest+File.separator+rootPath);

        return new JData(1,"拷贝成功",targetFile.list());
    }

    //递归拷贝目录及文件
    private void recursiveCopy(String target,String dest) throws Exception{
        (new File(dest)).mkdir();

        File targetFile = new File(target);
        String[] files = targetFile.list();

        File temp = null;
        if (files != null) {
            for(int i=0;i<files.length;i++){
                if(files[i].endsWith(File.separator)){
                    temp = new File(target+files[i]);
                }else{
                    temp = new File(target+File.separator+files[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(dest+File.separator +(temp.getName()).toString());
                    byte[] bytes = new byte[1024*5];
                    int len;
                    while ((len=input.read(bytes)) != -1){
                        output.write(bytes,0,len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }else{
                    recursiveCopy(target+File.separator+files[i],dest+File.separator+files[i]);
                }
            }
        }
    }

    //列出文件或者目录
    @GetMapping("/ls")
    public JData ls(@RequestParam(value = "path") String path){
        File file = new File(path);
        if(!file.exists()){
            return new JData(0,"文件不存在",0);
        }

        ArrayList<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

        File fa[] = file.listFiles();
        for(int i=0;i<fa.length;i++){
            File f = fa[i];
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("name",f.getName());
            map.put("path",f.getPath());
            map.put("isFile",f.isFile());
            map.put("isDirectory",f.isDirectory());
            map.put("lastModified",f.lastModified());
            map.put("canRead",f.canRead());
            map.put("canWrite",f.canWrite());
            map.put("canExecute",f.canExecute());
            data.add(map);
        }

        return new JData(1,"ok", data);
    }

}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
7 收藏
0
分享
返回顶部
顶部