FileUtil + FileUtils common writing reference
File permissions
Reference: https://www.breakyizhan.com/java/5013.html
Files and folders are the same thing here.
public static boolean setExecutable(String path) {
File file = FileUtils.getFile(path);
file.setReadable(true, false);
return file.setExecutable(true, false);
}
Create a file:
file.createNewFile()
Create a folder:
dir.mkdirs()
Deletion of files and folders:
file.delete()
When creating a new file, it is safe to use FileUtils.getFile(String path) instead of directly new
File information:
Get the latest modification time:
file.lastModified()
The return value is long, which is the number of milliseconds, as a reference: the number of milliseconds at the present moment is: System.currentTimeMillis(); the
format of the two is the same
Write file: keep adding to the end of the file in the form of append
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)))) {
writer.write(str);
} catch (IOException e) {
logger.error("Failed to close resource", e);
}
Way of flushing
try (FileWriter writer = new FileWriter(file)) {
writer.write("");
writer.flush();
} catch (IOException e) {
logger.error("IOException in writing file ", e);
}
The contents of multiple files (fpath) are unified into one file (resultFile), and the higher-performance FileChannel is used
File resultFile = FileUtils.getFile(resultPath);
//向resultFileChannel写入字节流
try (FileChannel resultFileChannel = new FileOutputStream(resultFile, true).getChannel()) {
for (int i = 0; i < fpaths.length; i++) {
//建立blk,从blk中读取字节流写入resultFileChannel
try (FileChannel blk = new FileInputStream(files[i]).getChannel()) {
// 在result的末尾插入blk大小的字节流
resultFileChannel.transferFrom(blk, resultFileChannel.size(), blk.size());
} catch (IOException e) {
logger.error("IOException occurs", e);
}
}
}
Query FileChannel: https://blog.csdn.net/developlee/article/details/90543160
Reference: https://blog.csdn.net/akon_vm/article/details/7429245
FileChannel is better than RandomAccessFile in read and write performance, yes So-called memory mapped files
Read the file:
StringBuffer sb = new StringBuffer();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String str = null;
str = reader.readLine();
if (str != null) {
sb.append(str);
}
str = reader.readLine();
while (str != null) {
sb.append(System.lineSeparator()).append(str);
str = reader.readLine();
}
} catch (IOException e) {
logger.error("IOException occurs!", e);
sb.setLength(0);
}
return sb.toString();
Use RandomAccessFile to read a fixed value from back to front, such as 10 here:
long pos = 0L;
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
long len = raf.length();
if (len == 0) {
return 0;
} else {
pos = len - 1;
while (pos-- > 0) {
raf.seek(pos);
if (raf.read() == 10) {
break;
}
}
return pos + 1;
}
}