Java文件操作

解压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对比表:

FileChannelRandomAccessFilePOSIX 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

这个可以实现应用的滚动日志。通常会删除比如一个月之前的日志,确保日志文件不会膨胀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值