Java IO 概述

本文深入探讨 Java IO 流的使用,包括 InputStream 和 OutputStream 的基础应用,Reader 和 Writer 的高级特性,以及如何高效地读写文件。同时,介绍了 Apache Commons IO 库的便捷性,提供了简化 IO 操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Stream

java.lang.Object

-> java.io.inputstream

This abstract class is the superclass of all classes representing an input stream of bytes.

也就是说,这是一切io操作的都是stream

最常见的subclass就是FileInputStream。



如何操作stream--reader和writer

java.io.reader -- Abstract class for reading character streams.

我见到的有:

reader = new BufferedReader(new InputStreamReader(new FileInputStream(file));

看看这一层包一层的效果~~到现在我看到只有FileInputStream(file)可以读file,所以读文件输出stream的时候必须用这个。

BufferedReader reads text from a character-input stream, buffering characters so as to provide for theefficient reading of characters, arrays, and lines. 因此在读取大文件的时候使用BufferedReader效率更高。

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specifiedcharset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider usingFileReader.

所以上面这行代码考虑到了字符转换和用buffer提高效率。

 

writer和reader是很类似的。从结构到用法。就不说太多了。下面是writer的一个简单例子。

  public static void main(String[] args) {

	  try {
		FileOutputStream out = new FileOutputStream("test.txt");
		out.write("write this words to file".getBytes());
		out.close();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }


注意使用了stream, reader, writer之后一定要close掉!!!

 

更简单的IO方法

java.io.FileReader 和 FileWriter分别继承了inputStreamReader 和 outputStreamWriter.  可以直接实现对文件的读写。

FileWriter

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

String content = "ABC";

FileWriter writer= new FileWriter(String );
    writer.write(content);
    writer.flush();
    writer.close();


Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only oneFileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.


Apache commons IO

前面所说都是java的标准库,而有人觉得不够方便,因此apache写了一套IO APIs,现在在广泛使用。

http://commons.apache.org/io/

API:

http://commons.apache.org/io/api-release/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值