JAVA对文件的一些操作

JAVA学习网 2020-08-29 14:36:02

在一般开发工作中,对文件的操作非常频繁,现根据各人总结一些常用的方法,有不对的还望各位指出

1,java中提供了io类库,跟多的还请自行百度或者查看java手册

 1 package com.spyang.config;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.lang.reflect.Array;
 6 import java.text.DecimalFormat;
 7 import java.util.ArrayList;
 8 import java.util.Arrays;
 9 import java.util.List;
10 
11 /**
12  * ************************************************
13  * 功能描述:   TODO 文件基本处理
14  *
15  * @author shuangping.yang
16  * @version 1.0
17  * @ClassName test
18  * @date 2020-8-28 创建文件
19  * @see ************************************************
20  */
21 public class test {
22     public static void main(String[] args) throws IOException {
23         //根据文件地址获取文件
24         String filePath = "F:\\test.xlsx";
25         String newFilePath = "F:\\test\\newTest.xlsx";
26         File file = new File(filePath);
27         // 判断文件是否存在
28         if (file.exists()) {
29             System.out.println("是否文件:" + file.isFile());
30             System.out.println("是否是文件夹:" + file.isDirectory());
31             System.out.println("文件路径:" + file.getPath());
32             System.out.println("文件名称:" + file.getName());
33             DecimalFormat df = new DecimalFormat("#.00");
34             System.out.println("文件的大小:" + df.format((double) file.length() / 1024) + "KB");
35             List<String> strArray = new ArrayList<String>(Arrays.asList(file.getName().split("\\.")));
36             System.out.println("文件后缀:" + strArray.get(1));
37             File mkdirs = new File("F:\\test");
38             File newFile = new File(newFilePath);
39             System.out.println("创建一个新的文件夹:" + mkdirs.mkdirs());
40             System.out.println("创建一个新的文件:" + newFile.createNewFile());
41             File newName = new File("F:\\newTest.xlsx");
42             System.out.println("重命名文件:" + file.renameTo(newName));
43         }
44     }
45 }

2,一个简单的文件上传

 1 package com.spyang.config;
 2 
 3 import org.springframework.util.StringUtils;
 4 import org.springframework.web.multipart.MultipartFile;
 5 
 6 import java.io.File;
 7 import java.io.FileOutputStream;
 8 import java.io.InputStream;
 9 import java.io.OutputStream;
10 
11 /**
12  * ************************************************
13  * 功能描述:   TODO 文件基本处理
14  *
15  * @author shuangping.yang
16  * @version 1.0
17  * @ClassName test
18  * @date 2020-8-28 创建文件
19  * @see ************************************************
20  */
21 public class test {
22     /**
23      * 上传文件
24      *
25      * @param attachmentLists
26      * @return
27      */
28     public void upFile(MultipartFile attachmentLists) {
29         try {
30             //如果文件不为空,写入上传路径
31             if (!attachmentLists.isEmpty()) {
32                 String filename = attachmentLists.getOriginalFilename();
33                 if (!StringUtils.hasText(filename)) {
34                     System.out.println("文件不存在" + filename);
35                 }
36                 //文件上传到指定的路径中test中
37                 filename = "F:\\test" + "/" + filename;
38                 File file = null;
39                 InputStream ins = null;
40                 ins = attachmentLists.getInputStream();
41                 file = new File(filename);
42                 //判断路径是否存在,如果不存在就创建一个
43                 if (!file.getParentFile().exists()) {
44                     file.getParentFile().mkdirs();
45                 }
46                 inputStreamToFile(ins, file);
47                 ins.close();
48             }
49             System.out.println("文件上传成功");
50         } catch (Exception e) {
51             System.out.println("上传文件异常:{}{}" + e.getMessage());
52         }
53     }
54 
55     private void inputStreamToFile(InputStream ins, File file) {
56         try {
57             //装换为文件输出流的方式写文件
58             OutputStream os = new FileOutputStream(file);
59             int bytesRead = 0;
60             byte[] buffer = new byte[8192];
61             while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
62                 os.write(buffer, 0, bytesRead);
63             }
64             os.close();
65             ins.close();
66         } catch (Exception e) {
67             e.printStackTrace();
68 
69         }
70     }
71 }

3,文件删除功能

 1 package com.spyang.config;
 2 
 3 import java.io.File;
 4 import java.util.ArrayList;
 5 import java.util.Arrays;
 6 import java.util.List;
 7 import java.util.stream.IntStream;
 8 
 9 /**
10  * ************************************************
11  * 功能描述:   TODO
12  *
13  * @author shuangping.yang
14  * @version 1.0
15  * @ClassName DelFile
16  * @date 2020.08.28 下午 04:46 创建文件
17  * @see ************************************************
18  */
19 public class DelFile {
20 
21     /**
22      * 删除单个文件
23      *
24      * @param sPath 被删除文件的文件名
25      * @return 单个文件删除成功返回true,否则返回false
26      */
27     public boolean deleteFile(String sPath) {
28         File file = new File(sPath);
29         String parentPath = file.getParent();
30         // 路径为文件且不为空则进行删除
31         if (file.isFile() && file.exists()) {
32             file.delete();
33             //清除上级空文件夹
34             clearFolder(new File(parentPath));
35             return true;
36         }
37         return false;
38     }
39 
40     /**
41      * 判断上级目录是否存在文件,不存在则清除空文件夹
42      *
43      * @param dir 文件
44      */
45     public static void clearFolder(File dir) {
46         if (dir.isDirectory()) {
47             String[] fileList = dir.list();
48             if (fileList.length == 0) {
49                 if (dir.isDirectory() && dir.delete()) {
50                     System.out.println("【{}】文件夹清除成功!" + dir.getPath());
51                 }
52             } else {
53                 System.out.println("该目录下存在文件,不能删除!");
54             }
55         }
56     }
57 
58     /**
59      * 递归清除空文件夹
60      *
61      * @param dir 文件
62      */
63     public static void recursionClearFolder(File dir) {
64         File[] dirs = dir.listFiles();
65         if (null != dirs) {
66             IntStream.range(0, dirs.length).
67                     filter(i -> dirs[i].isDirectory())
68                     .mapToObj(i -> dirs[i])
69                     .forEach(DelFile::recursionClearFolder);
70             if (dir.isDirectory() && dir.delete()) {
71                 System.out.println("【{}】文件夹清除成功!" + dir.getPath());
72             }
73         }
74     }
75 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

阅读(2427) 评论(0)