1. 读取文件比如本地的json数据,本地文本等
2. 写入文件
3. 复制文件
4. 移动文件
5. 删除文件
import com.alibaba.fastjson.util.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 文件工具类
*/
public class FileUtil {
private static Logger logger = Logger.getLogger(FileUtil.class);
// 文件扩展分隔符
private final static String FILE_EXTENSION_SEPARATOR = ".";
/**
* 读取文件
* @param filePath 文件路径
* @param charsetName 编码名称
* @return
*/
public static String readFile(String filePath, String charsetName) {
File file = new File(filePath);
StringBuilder fileContent = new StringBuilder();
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
return fileContent.toString();
} catch (Exception e) {
logger.error(e.getMessage());
return null;
} finally {
IOUtils.close(reader);
}
}
/**
* 读取文件转化为字符串列表
* @param filePath 文件路径
* @param charsetName 编码名称
* @return
*/
public static List<String> readFileToList(String filePath, String charsetName) {
File file = new File(filePath);
List<String> fileContent = new ArrayList<String>();
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
fileContent.add(line);
}
return fileContent;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
} finally {
IOUtils.close(reader);
}
}
/**
* 将内容写入文件
* @param filePath 文件路径
* @param content 写入的内容
* @param append 如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
* @return
*/
public static boolean writeFile(String filePath, String content, boolean append){
if (StringUtils.isEmpty(content)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
fileWriter.write(content);
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
} finally {
IOUtils.close(fileWriter);
}
}
/**
* 将字符串列表写入文件
* @param filePath 文件路径
* @param contentList 字符串列表
* @param append 如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
* @return
*/
public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
if (contentList == null || contentList.size() == 0) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
int i = 0;
for (String line : contentList) {
if (i++ > 0) {
fileWriter.write("\r\n");
}
fileWriter.write(line);
}
return true;
} catch (IOException e) {
logger.error(e.getMessage());
return false;
} finally {
IOUtils.close(fileWriter);
}
}
/**
* 将InputStream写入文件中,首先清除文件中的内容,在进行写入
* @param file
* @param stream
* @return
*/
public static boolean writeFile(File file, InputStream stream){
return writeFile(file, stream, false);
}
/**
* 将内容写入文件,首先清除文件中的内容,在进行写入
* @param filePath
* @param content
* @return
*/
public static boolean writeFile(String filePath, String content){
return writeFile(filePath, content, false);
}
/**
* 将字符串列表写入文件,首先清除文件中的内容,在进行写入
* @param filePath
* @param contentList
* @return
*/
public static boolean writeFile(String filePath, List<String> contentList){
return writeFile(filePath, contentList, false);
}
/**
* 将InputStream写入文件中,首先清除文件中的内容,在进行写入
* @param filePath
* @param stream
* @return
*/
public static boolean writeFile(String filePath, InputStream stream){
return writeFile(filePath != null ? new File(filePath) : null, stream, false);
}
/**
* 将InputStream写入文件中
* @param file 文件
* @param stream 流
* @param append 如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
* @return
*/
public static boolean writeFile(File file, InputStream stream, boolean append){
OutputStream o = null;
try {
makeDirs(file.getAbsolutePath());
o = new FileOutputStream(file, append);
byte data[] = new byte[1024];
int length = -1;
while ((length = stream.read(data)) != -1) {
o.write(data, 0, length);
}
o.flush();
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (IOException e) {
logger.error(e.getMessage());
return false;
} finally {
IOUtils.close(o);
IOUtils.close(stream);
}
}
/**
* 复制文件
* @param sourceFilePath 源文件路径
* @param destFilePath 目的文件路径
* @return
*/
public static boolean copyFile(String sourceFilePath, String destFilePath){
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourceFilePath);
} catch (Exception ex) {
logger.error(ex.getMessage());
return false;
}
return writeFile(destFilePath, inputStream);
}
/**
* 删除文件
* @param path
* @return
*/
public static boolean deleteFile(String path){
if (StringUtils.isEmpty(path)) {
return true;
}
File file = new File(path);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFile(f.getAbsolutePath());
}
}
return file.delete();
}
/**
* 移动文件
* @param srcFile
* @param destFile
*/
public static void moveFile(File srcFile, File destFile){
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}
public static void moveFile(String sourceFilePath, String destFilePath){
if (StringUtils.isEmpty(sourceFilePath) || StringUtils.isEmpty(destFilePath)) {
logger.error("Both sourceFilePath and destFilePath cannot be null");
}
moveFile(new File(sourceFilePath), new File(destFilePath));
}
/**
* 获取文件名称,包括后缀
* <pre>
* getFileName(null) = null
* getFileName("") = ""
* getFileName(" ") = " "
* getFileName("a.mp3") = "a.mp3"
* getFileName("a.b.rmvb") = "a.b.rmvb"
* getFileName("abc") = "abc"
* getFileName("c:\\") = ""
* getFileName("c:\\a") = "a"
* getFileName("c:\\a.b") = "a.b"
* getFileName("c:a.txt\\a") = "a"
* getFileName("/home/admin") = "admin"
* getFileName("/home/admin/a.txt/b.mp3") = "b.mp3"
* </pre>
* @param filePath 文件路径
* @return
*/
public static String getFileName(String filePath){
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
}
/**
* 获取文件名称,不带有后缀
* <pre>
* getFileNameWithoutExtension(null) = null
* getFileNameWithoutExtension("abc") = "abc"
* getFileNameWithoutExtension("a.mp3") = "a"
* getFileNameWithoutExtension("a.b.rmvb") = "a.b"
* getFileNameWithoutExtension("c:\\a.b") = "a"
* getFileNameWithoutExtension("/home/admin") = "admin"
* getFileNameWithoutExtension("/home/admin/a.txt/b.mp3") = "b"
* </pre>
* @param filePath 文件路径
* @return
*/
public static String getFileNameWithoutExtension(String filePath){
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
int filePosi = filePath.lastIndexOf(File.separator);
if (filePosi == -1) {
return (extenPosi == -1) ? filePath : filePath.substring(0, extenPosi);
}
if (extenPosi == -1) {
return filePath.substring(filePosi + 1);
}
return (filePosi < extenPosi) ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1);
}
/**
* 获取文件的目录名称
* @param filePath
* @return
*/
public static String getFolderName(String filePath){
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}
public static boolean makeDirs(String filePath){
String folderName = getFolderName(filePath);
if (StringUtils.isEmpty(folderName)) {
return false;
}
File folder = new File(folderName);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
}