转载请备注出处 谢谢!
1、文件基本操作工具类 ->创建、复制、删除、文件名称修改
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;
/**
* File文件、文件夹的基本操作, 创建、复制、删除、文件名称修改、文件下载
*/
public class FileUtils {
/**
* nio写文件
* @param fileName
* @param content
* @return
*/
public static void writeFile(String fileName, String content) {
//获取通道
FileOutputStream fos = null;
FileChannel channel = null;
ByteBuffer buffer = null;
try {
fos = new FileOutputStream(fileName);
channel = fos.getChannel();
buffer = ByteBuffer.wrap(content.getBytes());
//将内容写到缓冲区
fos.flush();
channel.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(fileName+"文件不存在", e);
} catch (IOException e) {
e.printStackTrace();
log.error("IO异常", e);
} finally {
try {
if (channel != null) {
channel.close();
}
} catch (IOException ee) {
log.error("IO异常", ee);
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException ee) {
log.error("IO异常", ee);
}
}
}
/**
* 读取文件
* @param fileName
* @return
*/
public static String readFile(String fileName) {
String str = null;
//获取通道
FileInputStream fis = null;
FileChannel channel = null;
try {
fis = new FileInputStream(fileName);
channel = fis.getChannel();
//指定缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//将通道中的数据读到缓冲区中
channel.read(buf);
byte[] arr = buf.array();
str = new String(arr);
} catch (FileNotFoundException e) {
log.error(fileName+"文件不存在", e);
} catch (IOException e) {
log.error("IO异常", e);
} finally {
try {
if (channel != null) {
channel.close();
}
} catch (IOException ee) {
log.error("IO异常", ee);
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException ee) {
ee.printStackTrace();
log.error("IO异常", ee);
}
}
return str.toString();
}
/**
* 如果目录不存在,就创建文件
* @param dirPath
* @return
*/
public static String mkdirs(String dirPath) {
try{
File file = new File(dirPath);
if(!file.exists()){
file.mkdirs();
}
}catch(Exception e){
e.printStackTrace();
}
return dirPath;
}
/**
* 判断文件是否存在
* @param filePath 文件路径
* @return
*/
public static boolean isExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
/**
* 判断是否是文件夹
* @param path
* @return
*/
public static boolean isDir(String path) {
File file = new File(path);
if(file.exists()){
return file.isDirectory();
文件操作工具类

最低0.47元/天 解锁文章
2923

被折叠的 条评论
为什么被折叠?



