解压zip压缩包
/**
* unzip the zip file
* @param sourcePath zip path
* @param dstPath destination path,it will be extracted to the subfolder of {@code dstPath},
* subfolder name is zip file name.
* @return whether success
**/
public static boolean unzipTo(String sourcePath, String dstPath) {
try {
ZipFile file = new ZipFile(sourcePath);
// create dst path
if (!new File(dstPath).mkdirs()){
if (!Files.exists(Paths.get(dstPath))) return false;
}
AtomicBoolean result= new AtomicBoolean(true);
file.stream().forEach(f -> {
try {
Path temp = Paths.get(String.format("%s%s%s", dstPath, BashShell.pathSeparator(), f.getName()));
if (f.isDirectory()) {
if (!Files.exists(temp)) Files.createDirectories(temp);
} else {
Files.createFile(temp);
Files.copy(file.getInputStream(f), temp, StandardCopyOption.REPLACE_EXISTING);
}
}catch (Exception e){
result.set(false);
}
});
return result.get();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
读写文件内容
/**
* read the file to raw byte array
* @param path target file path
* @return byte[] content in byte array
* @throws RuntimeException when path is not valid
* **/
public static byte[] readLines(String path) throws IOException {
Objects.requireNonNull(path);
Path pathTemp=Paths.get(path);
boolean exist= Files.exists(pathTemp);
if (!exist || !Files.isReadable(pathTemp)||Files.isDirectory(pathTemp)) throw new RuntimeException("path not exist or path is not readable,or directory");
return Files.readAllBytes(pathTemp);
}
/**
* read the file to raw byte array
* @param path target file path
* @param charset Charset to represent the String; it's optional,you can pass null in which case,the default charset is in use
* @return String content in specified charset
* @throws RuntimeException when path is not valid
* **/
public static String readLinesToString(String path,Charset charset) throws IOException {
Objects.requireNonNull(path);
Charset temp=charset == null ? Charset.defaultCharset():charset;
return new String(readLines(path),temp);
}
随机读写文件
C中有seek,read, write等操作,Java中也有对应的API。
文件IO API对比表:
FileChannel | RandomAccessFile | POSIX system call |
---|---|---|
read( ) | read( ) | read( ) |
write( ) | write( ) | write( ) |
size( ) | length( ) | fstat( ) |
position( ) | getFilePointer( ) | lseek( ) |
position (long newPosition) | seek( ) | lseek( ) |
truncate( ) | setLength( ) | ftruncate( ) |
force( ) | getFD().sync( ) | fsync( ) |
fsync
C中fsync用于数据库刷新page buffer里对文件的更新。在本地文件系统中,这个操作可以保证原子性,即全部刷新成功或者未刷新。
ftruncate
这个可以实现应用的滚动日志。通常会删除比如一个月之前的日志,确保日志文件不会膨胀。