JavaEE-文件存储

  1. 1. 文件存储工具整理
    1. 1.1. 工具类

文件存储工具整理

  • 随机名字存储
  • 指定文件名存储
  • 字节存储

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
* Created by admin on 2017/7/22.
*/
public class FileUtils {

public static String saveFileToPathWithRandomName(String content, String path)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 读取文件流并保持在指定路径
String filename = System.currentTimeMillis() + ".txt";
String mPath = path + File.separator
+ filename;
System.out.println(path);
OutputStream outputStream = new FileOutputStream(mPath);
byte[] buffer = content.getBytes(Charset.forName("utf-8"));
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
return filename;
}

public static String saveFileToPathWithName(String content, String path, String filename)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 读取文件流并保持在指定路径
String mPath = path + File.separator
+ filename;
System.out.println(path);
OutputStream outputStream = new FileOutputStream(mPath);
byte[] buffer = content.getBytes(Charset.forName("utf-8"));
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
return filename;
}

public static void deleteFiles(String dir) {
File file = new File(dir);
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File file1 : files) {
file1.delete();
}
}
}
}

public static String saveFile(byte[] data, String dirName, String fileName) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String realPath = request.getRealPath("");
String newpath = realPath + File.separator + dirName;
File file = new File(newpath);
if (!file.exists()) {
file.mkdirs();
}
String filePath = newpath + File.separator + fileName;
try {
FileOutputStream fos = new FileOutputStream(new File(filePath), false);
fos.write(data);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
}