com.gitee.cliveyuan.tools.FileTools Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-tools Show documentation
Show all versions of java-tools Show documentation
Some commonly used methods in java
package com.gitee.cliveyuan.tools;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 文件工具
*
* @author clive
* Created on 2018/07/23
* @since: 1.0
*/
public class FileTools extends FileUtils {
private static final String ENCODING = "UTF-8";
private FileTools() {
}
private static void validate(File file) {
Assert.notNull(file, "file can't be null");
Assert.isTrue(file.exists(), "file not exists: " + file.getAbsolutePath());
}
/**
* 读取文件为字符串 (UTF-8模式读取)
*
* @param file
* @throws IOException
*/
public static String readFileToString(File file) throws IOException {
validate(file);
return readFileToString(file, ENCODING);
}
/**
* 读取文件为字符串列表 (UTF-8模式读取)
*
* @param file
* @throws IOException
*/
public static List readFileToStringList(File file) throws IOException {
return readFileToStringList(file, ENCODING);
}
/**
* 读取文件为字符串列表
*
* @param file
* @throws IOException
*/
public static List readFileToStringList(File file, String encoding) throws IOException {
validate(file);
List list = new ArrayList<>();
try (LineIterator lineIterator = FileUtils.lineIterator(file, encoding)) {
while (lineIterator.hasNext()) list.add(lineIterator.nextLine());
}
return list;
}
/**
* 获取扩展名
*
* @param file
*/
public static String getExtension(File file) {
if (Objects.isNull(file)) return null;
return getExtension(file.getName());
}
/**
* 获取扩展名
*
* @param filePath
*/
public static String getExtension(String filePath) {
return filePath.substring(filePath.lastIndexOf(".") + 1);
}
}