Home  >  Article  >  Java  >  Java read and write file operations, including all io operations, introduction to the FileUtil tool

Java read and write file operations, including all io operations, introduction to the FileUtil tool

无忌哥哥
无忌哥哥Original
2018-07-20 10:45:081939browse

一、文件读写保存在开发中是非常重要的一环。记录一下 FileUtils工具类,非常好用的工具类。简化了代码。

maven依赖包为:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

1.图片转换字节流,字节流转换为图片存储。

public static void main(String[] args) throws Exception{
    
    //优化前,将图片转换为字节流
    FileInputStream fin = new FileInputStream(new File("D:\\crt.bmp"));
    byte[] bytes  = new byte[fin.available()];
    fin.read(bytes);
    fin.close();

    //优化前,将字节写入文件
    FileOutputStream fout = new FileOutputStream(new File("D:\\crt111.bmp"));
    fout.write(bytes);
    fout.close();
    
    //优化后,将图片转换为字节流
    byte[] bytes2 =  FileUtils.readFileToByteArray(new File("D:\\crt.bmp"));
    
    //优化后,将字节流存储为图片文件
    FileUtils.writeByteArrayToFile(new File("D:\\crt222.bmp"),bytes2);

}

2.读取文件readLines按照行读,返回为list,写文件,写一个数组集合。都很简单,很好用,FileUtils.就可以看到各个方法。

The above is the detailed content of Java read and write file operations, including all io operations, introduction to the FileUtil tool. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn