您的位置:首页 > 编程语言 > Java开发

Java IO 概述

2011-04-23 10:02 204 查看
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 specified
charset
.
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 using
FileReader
.

所以上面这行代码考虑到了字符转换和用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: