文件
文件读取
package cn.hutool.core.io.file;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class FileReader extends FileWrapper {
private static final long serialVersionUID = 1L;
public static FileReader create(File file, Charset charset) {
return new FileReader(file, charset);
}
public static FileReader create(File file) {
return new FileReader(file);
}
public FileReader(File file, Charset charset) {
super(file, charset);
this.checkFile();
}
public FileReader(File file, String charset) {
this(file, CharsetUtil.charset(charset));
}
public FileReader(String filePath, Charset charset) {
this(FileUtil.file(filePath), charset);
}
public FileReader(String filePath, String charset) {
this(FileUtil.file(filePath), CharsetUtil.charset(charset));
}
public FileReader(File file) {
this(file, DEFAULT_CHARSET);
}
public FileReader(String filePath) {
this(filePath, DEFAULT_CHARSET);
}
public byte[] readBytes() throws IORuntimeException {
long len = this.file.length();
if (len >= 2147483647L) {
throw new IORuntimeException("File is larger then max array size");
} else {
byte[] bytes = new byte[(int)len];
FileInputStream in = null;
try {
in = new FileInputStream(this.file);
int readLength = in.read(bytes);
if ((long)readLength < len) {
throw new IOException(StrUtil.format("File length is [{}] but read [{}]!", new Object[]{len, readLength}));
}
} catch (Exception var10) {
throw new IORuntimeException(var10);
} finally {
IoUtil.close(in);
}
return bytes;
}
}
public String readString() throws IORuntimeException {
return new String(this.readBytes(), this.charset);
}
public <T extends Collection<String>> T readLines(T collection) throws IORuntimeException {
BufferedReader reader = null;
try {
reader = FileUtil.getReader(this.file, this.charset);
while(true) {
String line = reader.readLine();
if (line == null) {
Collection var4 = collection;
return var4;
}
collection.add(line);
}
} catch (IOException var8) {
throw new IORuntimeException(var8);
} finally {
IoUtil.close(reader);
}
}
public void readLines(LineHandler lineHandler) throws IORuntimeException {
BufferedReader reader = null;
try {
reader = FileUtil.getReader(this.file, this.charset);
IoUtil.readLines(reader, lineHandler);
} finally {
IoUtil.close(reader);
}
}
public List<String> readLines() throws IORuntimeException {
return (List)this.readLines((Collection)(new ArrayList()));
}
public <T> T read(FileReader.ReaderHandler<T> readerHandler) throws IORuntimeException {
BufferedReader reader = null;
Object result;
try {
reader = FileUtil.getReader(this.file, this.charset);
result = readerHandler.handle(reader);
} catch (IOException var8) {
throw new IORuntimeException(var8);
} finally {
IoUtil.close(reader);
}
return result;
}
public BufferedReader getReader() throws IORuntimeException {
return IoUtil.getReader(this.getInputStream(), this.charset);
}
public BufferedInputStream getInputStream() throws IORuntimeException {
try {
return new BufferedInputStream(new FileInputStream(this.file));
} catch (IOException var2) {
throw new IORuntimeException(var2);
}
}
public long writeToStream(OutputStream out) throws IORuntimeException {
return this.writeToStream(out, false);
}
public long writeToStream(OutputStream out, boolean isCloseOut) throws IORuntimeException {
Throwable var5;
try {
FileInputStream in = new FileInputStream(this.file);
Throwable var4 = null;
try {
var5 = IoUtil.copy(in, out);
} catch (Throwable var24) {
var5 = var24;
var4 = var24;
throw var24;
} finally {
if (in != null) {
if (var4 != null) {
try {
in.close();
} catch (Throwable var23) {
var4.addSuppressed(var23);
}
} else {
in.close();
}
}
}
} catch (IOException var26) {
throw new IORuntimeException(var26);
} finally {
if (isCloseOut) {
IoUtil.close(out);
}
}
return (long)var5;
}
private void checkFile() throws IORuntimeException {
if (!this.file.exists()) {
throw new IORuntimeException("File not exist: " + this.file);
} else if (!this.file.isFile()) {
throw new IORuntimeException("Not a file:" + this.file);
}
}
public interface ReaderHandler<T> {
T handle(BufferedReader var1) throws IOException;
}
}
文件写入
package cn.hutool.core.io.file;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class FileWriter extends FileWrapper {
private static final long serialVersionUID = 1L;
public static FileWriter create(File file, Charset charset) {
return new FileWriter(file, charset);
}
public static FileWriter create(File file) {
return new FileWriter(file);
}
public FileWriter(File file, Charset charset) {
super(file, charset);
this.checkFile();
}
public FileWriter(File file, String charset) {
this(file, CharsetUtil.charset(charset));
}
public FileWriter(String filePath, Charset charset) {
this(FileUtil.file(filePath), charset);
}
public FileWriter(String filePath, String charset) {
this(FileUtil.file(filePath), CharsetUtil.charset(charset));
}
public FileWriter(File file) {
this(file, DEFAULT_CHARSET);
}
public FileWriter(String filePath) {
this(filePath, DEFAULT_CHARSET);
}
public File write(String content, boolean isAppend) throws IORuntimeException {
BufferedWriter writer = null;
try {
writer = this.getWriter(isAppend);
writer.write(content);
writer.flush();
} catch (IOException var8) {
throw new IORuntimeException(var8);
} finally {
IoUtil.close(writer);
}
return this.file;
}
public File write(String content) throws IORuntimeException {
return this.write(content, false);
}
public File append(String content) throws IORuntimeException {
return this.write(content, true);
}
public <T> File writeLines(Iterable<T> list) throws IORuntimeException {
return this.writeLines(list, false);
}
public <T> File appendLines(Iterable<T> list) throws IORuntimeException {
return this.writeLines(list, true);
}
public <T> File writeLines(Iterable<T> list, boolean isAppend) throws IORuntimeException {
return this.writeLines(list, (LineSeparator)null, isAppend);
}
public <T> File writeLines(Iterable<T> list, LineSeparator lineSeparator, boolean isAppend) throws IORuntimeException {
PrintWriter writer = this.getPrintWriter(isAppend);
Throwable var5 = null;
try {
boolean isFirst = true;
Iterator var7 = list.iterator();
while(var7.hasNext()) {
T t = var7.next();
if (null != t) {
if (isFirst) {
isFirst = false;
if (isAppend && FileUtil.isNotEmpty(this.file)) {
this.printNewLine(writer, lineSeparator);
}
} else {
this.printNewLine(writer, lineSeparator);
}
writer.print(t);
writer.flush();
}
}
} catch (Throwable var16) {
var5 = var16;
throw var16;
} finally {
if (writer != null) {
if (var5 != null) {
try {
writer.close();
} catch (Throwable var15) {
var5.addSuppressed(var15);
}
} else {
writer.close();
}
}
}
return this.file;
}
public File writeMap(Map<?, ?> map, String kvSeparator, boolean isAppend) throws IORuntimeException {
return this.writeMap(map, (LineSeparator)null, kvSeparator, isAppend);
}
public File writeMap(Map<?, ?> map, LineSeparator lineSeparator, String kvSeparator, boolean isAppend) throws IORuntimeException {
if (null == kvSeparator) {
kvSeparator = " = ";
}
PrintWriter writer = this.getPrintWriter(isAppend);
Throwable var6 = null;
try {
Iterator var7 = map.entrySet().iterator();
while(var7.hasNext()) {
Entry<?, ?> entry = (Entry)var7.next();
if (null != entry) {
writer.print(StrUtil.format("{}{}{}", new Object[]{entry.getKey(), kvSeparator, entry.getValue()}));
this.printNewLine(writer, lineSeparator);
writer.flush();
}
}
} catch (Throwable var16) {
var6 = var16;
throw var16;
} finally {
if (writer != null) {
if (var6 != null) {
try {
writer.close();
} catch (Throwable var15) {
var6.addSuppressed(var15);
}
} else {
writer.close();
}
}
}
return this.file;
}
public File write(byte[] data, int off, int len) throws IORuntimeException {
return this.write(data, off, len, false);
}
public File append(byte[] data, int off, int len) throws IORuntimeException {
return this.write(data, off, len, true);
}
public File write(byte[] data, int off, int len, boolean isAppend) throws IORuntimeException {
try {
FileOutputStream out = new FileOutputStream(FileUtil.touch(this.file), isAppend);
Throwable var6 = null;
try {
out.write(data, off, len);
out.flush();
} catch (Throwable var16) {
var6 = var16;
throw var16;
} finally {
if (out != null) {
if (var6 != null) {
try {
out.close();
} catch (Throwable var15) {
var6.addSuppressed(var15);
}
} else {
out.close();
}
}
}
} catch (IOException var18) {
throw new IORuntimeException(var18);
}
return this.file;
}
public File writeFromStream(InputStream in) throws IORuntimeException {
return this.writeFromStream(in, true);
}
public File writeFromStream(InputStream in, boolean isCloseIn) throws IORuntimeException {
FileOutputStream out = null;
try {
out = new FileOutputStream(FileUtil.touch(this.file));
IoUtil.copy(in, out);
} catch (IOException var8) {
throw new IORuntimeException(var8);
} finally {
IoUtil.close(out);
if (isCloseIn) {
IoUtil.close(in);
}
}
return this.file;
}
public BufferedOutputStream getOutputStream() throws IORuntimeException {
try {
return new BufferedOutputStream(new FileOutputStream(FileUtil.touch(this.file)));
} catch (IOException var2) {
throw new IORuntimeException(var2);
}
}
public BufferedWriter getWriter(boolean isAppend) throws IORuntimeException {
try {
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileUtil.touch(this.file), isAppend), this.charset));
} catch (Exception var3) {
throw new IORuntimeException(var3);
}
}
public PrintWriter getPrintWriter(boolean isAppend) throws IORuntimeException {
return new PrintWriter(this.getWriter(isAppend));
}
private void checkFile() throws IORuntimeException {
Assert.notNull(this.file, "File to write content is null !", new Object[0]);
if (this.file.exists() && !this.file.isFile()) {
throw new IORuntimeException("File [{}] is not a file !", new Object[]{this.file.getAbsoluteFile()});
}
}
private void printNewLine(PrintWriter writer, LineSeparator lineSeparator) {
if (null == lineSeparator) {
writer.println();
} else {
writer.print(lineSeparator.getValue());
}
}
}
文件追加
package cn.hutool.core.io.file;
import cn.hutool.core.thread.lock.LockUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import java.io.File;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
public class FileAppender implements Serializable {
private static final long serialVersionUID = 1L;
private final FileWriter writer;
private final int capacity;
private final boolean isNewLineMode;
private final List<String> list;
private final Lock lock;
public FileAppender(File destFile, int capacity, boolean isNewLineMode) {
this(destFile, CharsetUtil.CHARSET_UTF_8, capacity, isNewLineMode);
}
public FileAppender(File destFile, Charset charset, int capacity, boolean isNewLineMode) {
this(destFile, charset, capacity, isNewLineMode, (Lock)null);
}
public FileAppender(File destFile, Charset charset, int capacity, boolean isNewLineMode, Lock lock) {
this.capacity = capacity;
this.list = new ArrayList(capacity);
this.isNewLineMode = isNewLineMode;
this.writer = FileWriter.create(destFile, charset);
this.lock = (Lock)ObjectUtil.defaultIfNull(lock, LockUtil::getNoLock);
}
public FileAppender append(String line) {
if (this.list.size() >= this.capacity) {
this.flush();
}
this.lock.lock();
try {
this.list.add(line);
} finally {
this.lock.unlock();
}
return this;
}
public FileAppender flush() {
this.lock.lock();
try {
PrintWriter pw = this.writer.getPrintWriter(true);
Throwable var2 = null;
try {
Iterator var3 = this.list.iterator();
while(var3.hasNext()) {
String str = (String)var3.next();
pw.print(str);
if (this.isNewLineMode) {
pw.println();
}
}
} catch (Throwable var19) {
var2 = var19;
throw var19;
} finally {
if (pw != null) {
if (var2 != null) {
try {
pw.close();
} catch (Throwable var18) {
var2.addSuppressed(var18);
}
} else {
pw.close();
}
}
}
this.list.clear();
} finally {
this.lock.unlock();
}
return this;
}
}
文件跟随
package cn.hutool.core.io.file;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Stack;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class Tailer implements Serializable {
private static final long serialVersionUID = 1L;
public static final LineHandler CONSOLE_HANDLER = new Tailer.ConsoleLineHandler();
private final Charset charset;
private final LineHandler lineHandler;
private final int initReadLine;
private final long period;
private final RandomAccessFile randomAccessFile;
private final ScheduledExecutorService executorService;
public Tailer(File file, LineHandler lineHandler) {
this(file, lineHandler, 0);
}
public Tailer(File file, LineHandler lineHandler, int initReadLine) {
this(file, CharsetUtil.CHARSET_UTF_8, lineHandler, initReadLine, DateUnit.SECOND.getMillis());
}
public Tailer(File file, Charset charset, LineHandler lineHandler) {
this(file, charset, lineHandler, 0, DateUnit.SECOND.getMillis());
}
public Tailer(File file, Charset charset, LineHandler lineHandler, int initReadLine, long period) {
checkFile(file);
this.charset = charset;
this.lineHandler = lineHandler;
this.period = period;
this.initReadLine = initReadLine;
this.randomAccessFile = FileUtil.createRandomAccessFile(file, FileMode.r);
this.executorService = Executors.newSingleThreadScheduledExecutor();
}
public void start() {
this.start(false);
}
public void start(boolean async) {
try {
this.readTail();
} catch (IOException var7) {
throw new IORuntimeException(var7);
}
LineReadWatcher lineReadWatcher = new LineReadWatcher(this.randomAccessFile, this.charset, this.lineHandler);
ScheduledFuture<?> scheduledFuture = this.executorService.scheduleAtFixedRate(lineReadWatcher, 0L, this.period, TimeUnit.MILLISECONDS);
if (!async) {
try {
scheduledFuture.get();
} catch (ExecutionException var5) {
throw new UtilException(var5);
} catch (InterruptedException var6) {
}
}
}
public void stop() {
this.executorService.shutdown();
}
private void readTail() throws IOException {
long len = this.randomAccessFile.length();
if (this.initReadLine > 0) {
Stack<String> stack = new Stack();
long start = this.randomAccessFile.getFilePointer();
long nextEnd = len - 1L < 0L ? 0L : len - 1L;
this.randomAccessFile.seek(nextEnd);
int currentLine = 0;
while(nextEnd > start && currentLine <= this.initReadLine) {
int c = this.randomAccessFile.read();
String line;
if (c == 10 || c == 13) {
line = FileUtil.readLine(this.randomAccessFile, this.charset);
if (null != line) {
stack.push(line);
}
++currentLine;
--nextEnd;
}
--nextEnd;
this.randomAccessFile.seek(nextEnd);
if (nextEnd == 0L) {
line = FileUtil.readLine(this.randomAccessFile, this.charset);
if (null != line) {
stack.push(line);
}
break;
}
}
while(!stack.isEmpty()) {
this.lineHandler.handle((String)stack.pop());
}
}
try {
this.randomAccessFile.seek(len);
} catch (IOException var11) {
throw new IORuntimeException(var11);
}
}
private static void checkFile(File file) {
if (!file.exists()) {
throw new UtilException("File [{}] not exist !", new Object[]{file.getAbsolutePath()});
} else if (!file.isFile()) {
throw new UtilException("Path [{}] is not a file !", new Object[]{file.getAbsolutePath()});
}
}
public static class ConsoleLineHandler implements LineHandler {
public ConsoleLineHandler() {
}
public void handle(String line) {
Console.log(line);
}
}
}
文件名工具
package cn.hutool.core.io.file;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import java.io.File;
import java.util.regex.Pattern;
public class FileNameUtil {
public static final String EXT_JAVA = ".java";
public static final String EXT_CLASS = ".class";
public static final String EXT_JAR = ".jar";
public static final char UNIX_SEPARATOR = '/';
public static final char WINDOWS_SEPARATOR = '\\';
private static final Pattern FILE_NAME_INVALID_PATTERN_WIN = Pattern.compile("[\\\\/:*?\"<>|\r\n]");
private static final CharSequence[] SPECIAL_SUFFIX = new CharSequence[]{"tar.bz2", "tar.Z", "tar.gz", "tar.xz"};
public FileNameUtil() {
}
public static String getName(File file) {
return null != file ? file.getName() : null;
}
public static String getName(String filePath) {
if (null == filePath) {
return null;
} else {
int len = filePath.length();
if (0 == len) {
return filePath;
} else {
if (CharUtil.isFileSeparator(filePath.charAt(len - 1))) {
--len;
}
int begin = 0;
for(int i = len - 1; i > -1; --i) {
char c = filePath.charAt(i);
if (CharUtil.isFileSeparator(c)) {
begin = i + 1;
break;
}
}
return filePath.substring(begin, len);
}
}
}
public static String getSuffix(File file) {
return extName(file);
}
public static String getSuffix(String fileName) {
return extName(fileName);
}
public static String getPrefix(File file) {
return mainName(file);
}
public static String getPrefix(String fileName) {
return mainName(fileName);
}
public static String mainName(File file) {
return file.isDirectory() ? file.getName() : mainName(file.getName());
}
public static String mainName(String fileName) {
if (null == fileName) {
return null;
} else {
int len = fileName.length();
if (0 == len) {
return fileName;
} else {
CharSequence[] var2 = SPECIAL_SUFFIX;
int end = var2.length;
for(int var4 = 0; var4 < end; ++var4) {
CharSequence specialSuffix = var2[var4];
if (StrUtil.endWith(fileName, "." + specialSuffix)) {
return StrUtil.subPre(fileName, len - specialSuffix.length() - 1);
}
}
if (CharUtil.isFileSeparator(fileName.charAt(len - 1))) {
--len;
}
int begin = 0;
end = len;
for(int i = len - 1; i >= 0; --i) {
char c = fileName.charAt(i);
if (len == end && '.' == c) {
end = i;
}
if (CharUtil.isFileSeparator(c)) {
begin = i + 1;
break;
}
}
return fileName.substring(begin, end);
}
}
}
public static String extName(File file) {
if (null == file) {
return null;
} else {
return file.isDirectory() ? null : extName(file.getName());
}
}
public static String extName(String fileName) {
if (fileName == null) {
return null;
} else {
int index = fileName.lastIndexOf(".");
if (index == -1) {
return "";
} else {
int secondToLastIndex = fileName.substring(0, index).lastIndexOf(".");
String substr = fileName.substring(secondToLastIndex == -1 ? index : secondToLastIndex + 1);
if (StrUtil.containsAny(substr, SPECIAL_SUFFIX)) {
return substr;
} else {
String ext = fileName.substring(index + 1);
return StrUtil.containsAny(ext, new char[]{'/', '\\'}) ? "" : ext;
}
}
}
}
public static String cleanInvalid(String fileName) {
return StrUtil.isBlank(fileName) ? fileName : ReUtil.delAll(FILE_NAME_INVALID_PATTERN_WIN, fileName);
}
public static boolean containsInvalid(String fileName) {
return !StrUtil.isBlank(fileName) && ReUtil.contains(FILE_NAME_INVALID_PATTERN_WIN, fileName);
}
public static boolean isType(String fileName, String... extNames) {
return StrUtil.equalsAnyIgnoreCase(extName(fileName), extNames);
}
}