一、简介

在实际工作中,基本上每个项目难免都会有文件相关的操作,比如文件上传、文件下载等,这些操作都是使用IO流进行操作的,本文将通过简单的示例对常用的一些IO流进行总结。

二、使用详解

【a】FileInputStream与FileOutputStream

首先通过查看jdk文档,了解下FileInputStream与FileOutputStream的操作方法:

FileInputStream:

FileOutputStream:

输入流主要是通过read读取文件,输出流主要是通过write写出到文件。

下面以文件拷贝的示例说明FileinputStream与FileOutputStream的使用方法:

public class CopyFileUtils {/**** @param sourceFile* @param destFile* @throws IOException*/public static void copyFile(File sourceFile, File destFile) throws IOException {//1. 源文件必须存在并且是文件if (!sourceFile.exists() || !sourceFile.isFile()) {System.out.println("源文件必须存在并且是文件");return;}if (destFile.isDirectory()) {return;}//2. 建立与文件的联系InputStream is = new FileInputStream(sourceFile);OutputStream os = new FileOutputStream(destFile);//实际接收长度int len = 0;//缓冲字节数组byte[] buffer = new byte[1024];//3. 循环读取文件while ((len = is.read(buffer)) != -1) {//4. 通过OutputStream写出到文件os.write(buffer, 0, len);}// 5. 关闭流os.flush();os.close();is.close();}public static void copyFile(String sourcePath, String destPath) throws IOException {//1. 源文件、目标文件建立联系File sourceFile = new File(sourcePath);File destFile = new File(destPath);copyFile(sourceFile, destFile);}}

测试:

public class TestCopyFileUtils {public static void main(String[] args) {try {CopyFileUtils.copyFile("d:/aaa/a.txt", "d:/aaa/b.txt");} catch (IOException e) {System.out.println("文件拷贝失败!");e.printStackTrace();}}}

运行结果:

下面以文件夹拷贝的示例来巩固FileinputStream与FileOutputStream的使用方法:

public class CopyDirUtils {public static void copyDir(String sourcePath, String destPath) throws IOException {//1. 建立与文件的联系File sourceFile = new File(sourcePath);File destFile = new File(destPath);//如果源文件是一个文件夹if (sourceFile.isDirectory()) {destFile = new File(destFile, sourceFile.getName());}copyDirDetail(sourceFile, destFile);}private static void copyDirDetail(File sourceFile, File destFile) throws IOException {//2. 如果源文件是一个文件,则直接拷贝即可if (sourceFile.isFile()) {//拷贝文件CopyFileUtils.copyFile(sourceFile, destFile);} else if (sourceFile.isDirectory()) {//3. 如果源文件是一个文件夹,那么需要确保目标文件夹存在destFile.mkdirs();//4. 使用listFiles递归调用copyDirDetail拷贝文件夹以及子文件for (File subFile : sourceFile.listFiles()) {copyDirDetail(subFile, new File(destFile, subFile.getName()));}}}}

测试:

public class TestCopyDirUtils {public static void main(String[] args) throws IOException {String sourcePath = "d:/aaa";String destPath = "d:/bbb";CopyDirUtils.copyDir(sourcePath, destPath);}}

运行结果:

【b】FileReader与FileWriter

FileReader与FileWriter并没有新增的方法,跟上面的用法基本类似,只是FileReader与FileWriter只能读取纯文本的文件。

下面分别讲解FileReader与FileWriter的基础用法:

/*** @Description: 纯文本读取* @Author: weishihuai* @Date: 2018/11/1 20:40*/
public class FileReaderAndFileWriter {public static void main(String[] args) {//先写内容到文件writeFile();//再读取出来readFile();}/*** 把内容输出到文件*/public static void writeFile() {//1. 需要写出的目标文件路径File file = new File("d:/aaa/b.txt");Writer writer = null;try {//2. 建立与目标文件的联系writer = new FileWriter(file);//3. 使用write()直接写出字符串(只能写出纯文本内容)writer.write("hello world!!!!!!!!!");//4. 刷新流writer.flush();} catch (IOException e) {e.printStackTrace();} finally {//5. 关闭流if (null != writer) {try {writer.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 读取文件中的内容*/public static void readFile() {//1. 定义源文件路径File file = new File("d:/aaa/b.txt");Reader reader = null;try {//2. 建立与源文件的联系reader = new FileReader(file);//3. 字符缓存数组char[] buffer = new char[1024];//4. 定义实际接收长度int len = 0;//5. 循环读取文件内容while (-1 != (len = reader.read(buffer))) {System.out.println(new String(buffer));}} catch (java.io.IOException e) {e.printStackTrace();System.out.println("源文件读取失败");} finally {//6. 关闭流if (null != reader) {try {reader.close();} catch (IOException e) {e.printStackTrace();System.out.println("关闭流失败");}}}}}

运行结果:

【c】BufferedInputStream与BufferedOutStream

BufferedInputStream与BufferedOutStream是字节处理流,起到增强功能, 提高性能的作用。(推荐使用)

BufferedInputStream与BufferedOutStream的使用方法并没有太大区别,只是在原来FileInputStream与FileOutputStream的外层包裹一个处理流BufferInputStream与BufferOutStream而已,使用方法如下:

/*** @Description: 字节处理流(增强功能, 提高性能, 处理流一定要在节点流之上)* @Author: weishihuai* @Date: 2018/11/1 20:56*/
public class BufferInputStreamAndBufferOutStream {public static void main(String[] args) {//1.建立与源文件、目标文件的联系File sourceFile = new File("d:/aaa/a.txt");File destFile = new File("d:/aaa/aa.txt");InputStream inputStream = null;OutputStream outputStream = null;try {//在外层包裹一层处理流,加强功能inputStream = new BufferedInputStream(new FileInputStream(sourceFile));outputStream = new BufferedOutputStream(new FileOutputStream(destFile));//2. 定义缓冲字节数组以及实际接收长度lenbyte[] buffer = new byte[1024];int len = 0;//3. 循环读取文件中的内容while (-1 != (len = inputStream.read(buffer))) {//4.通过write将读取的内容写出到文件中outputStream.write(buffer, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//5. 关闭流if (null != outputStream) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (null != inputStream) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}
}

运行结果:

【d】BufferedReader与BufferedWriter

新增方法如下,其他方法都是从Reader或者Writer继承过来

BufferedReader:readLine() 读取一个文本行。

BufferedWriter:newLine() 写入一个行分隔符。

下面还是通过一个简单的示例讲解BufferedReader与BufferedWriter的使用方法:

public class BufferReaderAndBufferWriter {public static void main(String[] args) {//1. 建立与源文件、目标文件的联系File sourceFile = new File("d:/aaa/a.txt");File destFile = new File("d:/aaa/c.txt");BufferedReader reader = null;BufferedWriter writer = null;try {//2. 使用BufferedReader和BufferedWriter包裹FileReader和FileWriter//注意: 只能读取纯文本文件reader = new BufferedReader(new FileReader(sourceFile));writer = new BufferedWriter(new FileWriter(destFile));//3. 定义实际接收的字符串String str;//4. 使用reader.readLine()一行一行循环读取while (null != (str = reader.readLine())) {//5. 使用write()直接写出字符串到文件c.txtwriter.write(str);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//6. 关闭流if (null != writer) {try {writer.close();} catch (IOException e) {e.printStackTrace();}}if (null != reader) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}}
}

运行结果:

【e】InputStreamReader与OutputStreamWriter

转换流,主要用于解决文件读取或者写入出现的乱码问题。

出现乱码的问题一般有两种:

(1) 编码与解码的字符集不统一

(2) 字节数不够,长度丢失

下面我们通过示例讲解怎么解决乱码问题:

/*** @Description: 转换流(字节流 转换为 字符流)* @Author: weishihuai* @Date: 2018/11/1 21:22* <p>* 转换流: 主要用于解决乱码问题(保证源文件的编码集已知)*/
public class InputStreamReaderAndOutputStreamWriter {public static void main(String[] args) throws IOException {//1. 指定解码字符集BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/aaa/c.txt")), "utf-8"));//2. 定义实际接收字符串String string;//3. 一行一行读取纯文本文件内容while (null != (string = reader.readLine())) {System.out.println(string);}}}

如图,我们文件的编码为ANSI编码,我们指定的解码字符集为UTF-8,运行结果:

下面我们修改一下c.txt的编码字符集为UTF-8,再次运行程序,

如图,通过指定相同的编码与解码字符集,乱码问题就解决了。

【f】ByteArrayInputStream与ByteArrayOutputStream

ByteArrayInputStream与ByteArrayOutputStream是字节数组输入输出流,主要是将字节数组输出到文件中,再通过读取文件中的字节数组将内容读取出来。

/*** @Description: 字节数组流 字节流* @Author: weishihuai* @Date: 2018/11/2 20:43*/
public class ByteArrayInputStreamAndByteArrayOutputStream {public static void read(byte[] bytes) {ByteArrayInputStream bis = null;//1. 实际接收长度int len = 0;//字节数组byte[] bytes1 = new byte[1024];try {//2. 创建字节数组输入流bis = new ByteArrayInputStream(bytes);//3. 循环将文件中的字节数组读取出来while (-1 != (len = bis.read(bytes1))) {System.out.println(new String(bytes1));}} catch (IOException e) {e.printStackTrace();} finally {//4. 关闭流if (null != bis) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}}}public static byte[] write() {//字节数组byte[] dest;String string = "字节数组流 字节流 节点流";//需要写入文件的字节数组byte[] bytes = string.getBytes();ByteArrayOutputStream bos = new ByteArrayOutputStream();//使用write将字节数组写入到文件中bos.write(bytes, 0, bytes.length);//使用toByteArray()将输出流转化为字节数组dest = bos.toByteArray();return dest;}public static void main(String[] args) {
//        read();read(write());}}

运行结果:

下面通过示例讲解字节数组流与文件流对接:

/*** @Description: 字节数组流与文件流对接* @Author: weishihuai* @Date: 2018/11/2 20:57*/
public class ByteArrayToStream {public static void main(String[] args) {byte[] bytes = getBytesFromFile("d:aaa/a.txt");System.out.println(new String(bytes));toFileFromByteArray(bytes, "d:/aaa/t.txt");}/*** 从文件中读取到字节数组流中(文件输入流读取文件/字节数组输出流将文件写出到字节数组)** @param sourcePath 源文件路径* @return*/public static byte[] getBytesFromFile(String sourcePath) {File sourceFile = new File(sourcePath);byte[] dest;InputStream is = null;ByteArrayOutputStream bos = null;try {is = new BufferedInputStream(new FileInputStream(sourceFile));bos = new ByteArrayOutputStream();int len = 0;byte[] buffer = new byte[1024];while (-1 != (len = is.read(buffer))) {bos.write(buffer, 0, buffer.length);}bos.flush();dest = bos.toByteArray();return dest;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (null != bos) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}return null;}/*** 字节数组输出到文件(字节数组输入流将字节数组读取出来/文件输出流将字节数组写出到文件保存)** @param bytes 字节数组*/public static void toFileFromByteArray(byte[] bytes, String destPath) {OutputStream os = null;ByteArrayInputStream bis = new ByteArrayInputStream(bytes);int len = 0;byte[] buffer = new byte[1024];try {os = new FileOutputStream(new File(destPath));while (-1 != (len = bis.read(buffer))) {os.write(buffer, 0, len);}os.flush();} catch (IOException e) {e.printStackTrace();} finally {if (null != bis) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (null != os) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}}

运行结果:

三、总结

以上是工作中常用的IO流操作文件的方法,具体可以根据实际情况进行调整,本文是笔者在复习IO操作方法的一些总结,仅供大家学习参考,大家可以进行进一步优化,一起学习一起进步。

Java IO流常用操作方法总结相关推荐

  1. Java IO流学习总结(一)—— IO流分类和常用IO流汇总

    Java IO流学习总结(一)-- IO流分类和常用IO流汇总 IO流的分类: - 按流向分类:输入流.输出流 - 按操作对象分类:字节流.字符流 - 按功能分类:节点流.处理流 IO流的设计模式为装 ...

  2. Java IO流大闯关--IO流的常用实现类

    这个系列的博客主要是对Java高级编程中IO流相关的知识点做一个梳理,内容主要包括File类.IO流原理及流的分类.文件流.缓冲流.转换流.标准输入输出流.打印流.数据流.对象流.随机存取文件流.NI ...

  3. JAVA(IO流)知识整理

    IO (Input Output)流 IO流用来处理设备之间的数据传输: JAVA对数据的操作是通过流的方式: JAVA对于操作流的对象都在IO包中: 流按操作数据分为两种:字节流和字符流: 流按流向 ...

  4. java io流读写文件换行_java基础io流——OutputStream和InputStream的故事(温故知新)...

    io流概述: IO流用来处理设备之间的数据传输,上传文件和下载文件,Java对数据的操作是通过流的方式,Java用于操作流的对象都在IO包中. IO流分类 按照数据流向 输入流 读入数据 输出流 写出 ...

  5. 【JDK源码】java.io包常用类详解

    看完java.io的JDK源码,在网上发现一篇关于java.io中的类使用的文章总结的很全面,看完之后在原文的基础上加了一些自己的总结如下构成了本篇文章.原文地址 一.Java Io流 1. Java ...

  6. java io流 教程_Java基础教程:IO流与文件基础

    Java:IO流与文件基础 说明: 本章内容将会持续更新,大家可以关注一下并给我提供建议,谢谢啦. 走进流 什么是流 流:指的是从源到目的地的字节的有序序列. 在Java中,可以从其中读取一个字节序列 ...

  7. java IO流小结

    Java流操作有关的类或接口: Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...

  8. Java基础17:Java IO流总结

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/a724888/article/details/80201802 这位大侠,这是我的公众号:程序员江湖 ...

  9. Java IO流总结

    Java IO流分类以及主要使用方式如下: IO流 |--字节流 |--字节输入流 InputStream: int read();//一次读取一个字节 int read(byte[] bys);// ...

  10. java io流区别_Java中IO流的分类和BIO,NIO,AIO的区别

    到底什么是IO 我们常说的IO,指的是文件的输入和输出,但是在操作系统层面是如何定义IO的呢?到底什么样的过程可以叫做是一次IO呢? 拿一次磁盘文件读取为例,我们要读取的文件是存储在磁盘上的,我们的目 ...

最新文章

  1. 如何配置charles_抓包工具--charles(青花瓷)及获取AppStore数据包
  2. Educational Codeforces Round 40 (Rated for Div. 2)
  3. javascript Date object
  4. 大数据时代的全能日志分析专家--Splunk安装与实践
  5. ❤️什么是Java 面向对象《装、继承、多态、抽象》?建议收藏)❤️
  6. npm i 命令长时间卡住的解决办法
  7. Navicat Premium 15 for Mac(数据库管理工具)支持Big Sur
  8. java认证考试例题_2016年Java认证考试题(3)
  9. figure字体 latex_LaTeX字体设置(一)
  10. Python 轻松操作Excel,实现自动化办公
  11. 使用layui实现省市区及编码联动(引入第三方插件)
  12. K8s中Secrets
  13. transfromer-XL论文详解
  14. 全面解析流式大数据实时处理技术、平台及应用
  15. i3-10110U和i5 1035g7 哪个好
  16. 毕业一年,程序猿工作一年总结,有收获,有失去,有遗憾,但仍一往无前
  17. 技术概况python_《技》字意思读音、组词解释及笔画数 - 新华字典 - 911查询
  18. System services not available to Activities before onCreate()错误解决方法
  19. Java 之 Excel文件下载
  20. html转pdf 时插入文字,HTML转PDF字体的坑,搞了半天

热门文章

  1. 2021-09-01175. 组合两个表 SQL
  2. 15投影矩阵与Moore-Penrose逆(2)
  3. 12满秩分解与奇异值分解(1)
  4. android 监听网络的详细例子,android 短信 发送 监听 拦截等自己写的demo
  5. Torch环境搭建遇到的问题
  6. Torch7 out of memory 解决方法
  7. 【Codeforces Round #516_div2】Labyrinth【迷宫搜索】
  8. 有关深度估计的几篇文章的阅读笔记
  9. 边缘保留滤波matlab,【DIP】各种边缘保留滤波器一览
  10. php mysql多条件查询界面_PHP组合查询多条件查询实例代码