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

JAVA I/O

2016-04-24 21:44 204 查看

I. 简介

在程序执行的操作中,文件的读取和写入是执行得非常频繁的操作之一,本篇将会大致地介绍如何使用Java 提供的类完成读写操作.

同时因为读写操作的原理大致相似,因此本篇只会讲述读取操作.

II. 结构关系

java 的I/O 总体分为两大类,读取类(InputStream、Reader)和写出类(OutputStream、Writer).

InputStream 和Reader 不同在于,InputStream 是用于处理字节(byte),而Reader 则是用于处理字符以支持unicode 来是Java I/O 国际化. OutputStream 和Writer 同理.

实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操作的,但是字符流在操作的 时候下后是会用到缓冲区的,是通过缓冲区来操作文件的。

读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。

使用字节流好还是字符流好呢?

答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。

下面是这四个大类的关系图.



ByteArrayInputStream:处理字节数组的类,允许将内存的缓冲区当做InputStream使用。

StringBufferInputStream:将String转换成InputStream,内部实现用的是StringBuffer。

FileInputStream:从文件中读取数据。

PipedInputStream:用于从管道中读取数据。

SequenceInputStream:将多个流对象转化成一个InputStream。

FilterInputStream:装饰器类,为其它InputStream类提供功能。







再次强调的是,Reader 和Writer 是用于操作字符而不是字节。

III. 操作示例

1. 文件读取

public class InputTest {

public static void main(String [] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("/Users/Desktop/text.txt"));
String s = null;
StringBuilder sb = new StringBuilder();

while ((s = reader.readLine()) != null)
sb.append(s);

System.out.println(sb);
}
}


在这里,程序从test.txt 读取字符串,并
append()
到StringBuilder 中.

另一个值得注意的是,在创建BufferedReader 对象时,采用了装饰器设计模式(Decorator)来让BufferedReader 拥有更多的功能.

装饰器模式(Decorator)

2.标准I/O

public class StandardIO {

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
}
}


此处,程序从控制台直接读取.

同时因为控制台返回的是字节,所以需要InputStream 来包装.

在读取时,多采用BufferedReader,因为BufferedReader 可以一次读取一行或多个字符而不是一个个读取.

另需要注意的是,PrintWriter 能按照指定格式输出,所以输出会在很多时候采用PrintWriter.

IV. 文件读取实例

public class TextFile extends ArrayList<String> {

// Read a file as a String
public static String read(String filename) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new
FileReader(new File(filename).getAbsoluteFile()));
String s;
try {
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}

} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}

// Write a single file in one method call
public static void write(String fileName, String text) {
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

// Read a file,spilt by any regular expression
public TextFile(String fileName, String splitter) {
super(Arrays.asList(read(fileName).split(splitter)));
if (get(0).equals(""))
remove(0);
}

// Normally read by lines
public TextFile(String fileName) {
this(fileName, "\n");
}

public void write(String fileName) {
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
for (String item : this)
out.println(item);
} finally {
out.close();
}

} catch (IOException e) {
throw new RuntimeException(e);
}

}

// test,I have generated a file named data.d at the root
public static void main(String[] args) {

/* read() test */
System.out.println(read("data.d")); // testing is OK!

/* write() test */
write("out.d", "helloworld\negg"); // testing is OK!

/* constractor test */
TextFile tf = new TextFile("data.d"); // testing is OK!

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: