此文章主要是通过流将文件的内容读取出来和将上传的文件保存到本地(还有不足之处,后续更新)
一、文件的读取
注:方法参数为文件路径+文件全名(例:D:\fileReader\file.json)
/**
* 读取文件内容
* @param fileName 文件的本地路径(文件路径+文件全名)
* @return 文件内容
*/
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
// 获取文件对象
File file = new File(fileName);
if (!file.getParentFile().exists()) {// 如果父目录不存在,创建父目录
file.getParentFile().mkdirs();
}
if (file.exists()) {// 当文件存在时进行文件的读取
System.out.println("文件的本地路径:" + fileName);
// 获取文件的字节输入流并指定编码
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {// 通过流读取文件内容,读取为-1时读取完成
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();// 将读取的内容转换为字符串
} else {// 当文件不存在时创建一个内容为空的文件(前提是有父目录,上面已经创建好了)
file.createNewFile();
}
return jsonStr;// 将读到的文件内容进行返回
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
二、文件的保存
注:方法的参数为前端传过来的文件
/**
* 文件的上传
*
* @param file 前端传过来的文件
* @return 旧文件名、新文件名、文件保存的路径、异常
*/
public Map<String, String> fileWriter(MultipartFile file) {
// 返回的信息
Map<String, String> map = new HashMap<>();
if (file.isEmpty()) {
map.put("error", "上传的文件不能为空");
return map;
}
try {
// 得到文件的原始名
String oldName = file.getOriginalFilename();
// 得到文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// 上传文件
// file.getinputstream()的作用是获取文件的输入流,可以用来读取文件的内容;
InputStream stream = file.getInputStream();
// inputstream.available() 方法是用于检测从输入流中读取的字节数。
// 返回值是可以在当前时间读取的字节数。如果返回值是 0,则说明没有可用的字节可以读取。
byte[] bytes = new byte[stream.available()];
stream.read(bytes);//每次读取数据放到bytes数组,返回读取到数据的有效个数,读取到文件末尾返回-1。
// 生成UUID,拼接新的文件名、文件路径
String uuid = UUIDUtil.getUUID();
String newName = uuid + suffix;
String url = "D:\\fileWriter\\";
String path = url + newName;
// 获取文件对象
File newFile = new File(path);
// 获得文件的父级目录
File parent = newFile.getParentFile();
if (!parent.exists()) {// 如果父目录不存在,创建父目录
parent.mkdirs();
}
if (!newFile.exists()) {// 把图片保存到路径中(暂时只能上传图片,上传其他后续更新)
file.transferTo(newFile);
}
System.out.println("文件上传成功:" + newName);
map.put("oldFileName", oldName);
map.put("newFileName", newName);
map.put("newFilePath", path);
} catch (IOException e) {
map.put("error", "上传失败!");
e.printStackTrace();
return map;
}
return map;
}
注:读取文件转换为Base64并返回,代码如下
{// 读取文件转换为Base64并返回
String url = “C:\Users\Administrator\Desktop\小马\11.jpg”;
ByteArrayOutputStream baos = null;
try {
//获取图片类型
String suffix = url.substring(url.lastIndexOf(".") + 1);
//构建文件
File imageFile = new File(url);
//通过ImageIO把文件读取成BufferedImage对象
BufferedImage bufferedImage = ImageIO.read(imageFile);
//构建字节数组输出流
baos = new ByteArrayOutputStream();
//写入流
ImageIO.write(bufferedImage, suffix, baos);
//通过字节数组流获取字节数组
byte[] bytes = baos.toByteArray();
//获取JDK8里的编码器Base64.Encoder转为base64字符
String str = Base64.getEncoder().encodeToString(bytes);
return str;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、文件的删除
注:强制删除方法,无法删除有特殊权限的文件
/**
* 强制删除文件(本删除无法删除有特殊权限的文件)
*
* @param file 删除的文件夹或文件
*/
public Boolean deleteAllFilesOfDir(File file) {
// 判断文件是否存在
if (!file.exists())
return true;
// 判断文件是否为普通文件,并非文件夹
if (file.isFile()) {
boolean result = file.delete();
int tryCount = 0;
// 若删除失败则循环删除
while (!result && tryCount++ < 10) {
System.gc(); // 回收资源
result = file.delete();
}
if (result) {
return true;
}
}
// 获取文件夹下的文件,若不是文件夹则返回null
File[] files = file.listFiles();
if (null != files) {
for (File f : files) {
deleteAllFilesOfDir(f);
}
}
return file.delete();
}
UUID的获取,代码如下:
/**
* 生成uuid
* @return UUID
*/
public static String getUUID() {
String id = UUID.randomUUID().toString();
// 自动生成的UUID会自带符号‘-’,将符号替换成空串
// 替换前:3cc7bebf-87be-4e96-971f-025ecec185c0
// 替换后:3cc7bebf87be4e96971f025ecec185c0
id = id.replace("-", "");
return id;
}