java i o读写本地图片_Java常见的I/O读写方法

本文介绍了Java中四种基本的I/O操作:BufferedReader/Writer、nio Files、Scanner/PrintWriter以及Stream,分别用于读写本地文件。通过示例展示了如何按行或按字节读取和写入文件,并提供了性能对比的相关信息。
摘要由CSDN通过智能技术生成

目录

目录

0、写在前面

1、I/O

1.1、BufferedReader/Writer

1.1.1、BufferedReader

1.1.2、BufferedWriter

1.2、nio Files

1.2.1、read

1.2.2、write

1.3、Scanner/PrintWriter

1.3.1、Scanner

1.3.2、PrintWriter

1.4、Stream

1.4.1、InputStream

1.4.2、OutputStream

2、性能对比

0、写在前面

本节为软件构造系列Chapter8中的I/O性能部分的补充。

1、I/O

Java的I/O操作比较多,具体可以查询Java文档,Chrome中使用Ctrl+F查询io或nio即可。

这里主要介绍四种比较基本I/O方式,每种读写大致可以分为两种,按行读取和按字节读取,整体来说,大同小异。在此实现最基本的操作。

对于下面涉及的文件地址及File对象,在下面定义:

/* in file */

String filePathIn = "file.txt";

File fileIn = new File(filePath);

/* out file */

String filePathOut = "Out.txt";

File fileOut = new File(filePathOut);

1.1、BufferedReader/Writer

使用缓存区的读写方式。

1.1.1、BufferedReader

这里把brCh的大小设置为file.length(),一次性把文件加载到缓存中,之后可以进行解析等操作;也可以设置为特定的值(eg. 1024)等,分次加载。

/* new FileReader(fileIn)读写器 */

BufferedReader brIn = new BufferedReader(new FileReader(fileIn));

/* 文件大小 */

char[] brCh = new char[(int) fileIn.length()];

/* 读取进入brCh */

brIn.read(brCh);

brIn.close();

1.1.2、BufferedWriter

BufferedWriter bwOut = new BufferedWriter(new FileWriter(fileOut));

/* 将之前读取的brCh数组写入内存 */

bwOut.write(brCh);

bwOut.close();

1.2、nio Files

新IO操作,有很多改进,效率较高,操作较简单。

1.2.1、read

/* 按字节读取 */

byte[] nioBy = Files.readAllBytes(Paths.get(filePathIn));

/* 一次性读取所有行,可以使用for-each遍历 */

//String[] lines = Files.readAllLines(Paths.get(filePathIn));

1.2.2、write

/* 将之前读取的nioBy字节数组写入内存 */

Files.write(Paths.get(filePathOut), nioBy);

1.3、Scanner/PrintWriter

1.3.1、Scanner

/* 创建Scanner读取 */

Scanner scIn = new Scanner(fileIn);

/* 使用StringBuffer保存,避免生成太多临时变量 */

StringBuffer scStr = new StringBuffer();

String scLine;

/* 按行读取 */

while (scIn.hasNextLine()) {

scLine = scIn.nextLine();

scStr.append(scLine + "\n");

}

scIn.close();

1.3.2、PrintWriter

/* 写入器 */

PrintWriter pwOut = new PrintWriter(fileOut);

/* 将之前读取保存的StringBuffer转为String类型,然后写入文件 */

pwOut.write(scStr.toString());

pwOut.close();

1.4、Stream

使用文件流操作。

1.4.1、InputStream

InputStream disIn = new FileInputStream(fileIn);

/* 保存的字节数组 */

byte dosB[] = new byte[(int) fileIn.length()];

/* 一次加载进缓存 */

disIn.read(dosB);

disIn.close();

1.4.2、OutputStream

OutputStream dosOut = new FileOutputStream(fileOut);

/* 将读取的字节数组写入文件 */

dosOut.write(dosB);

dosOut.close();

2、性能对比

d44036ea8f252a088135965b896c7009.png

参考:

javadoc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值