java I/O 字节流和字符流的运用

来源:互联网 发布:传奇3数据库 编辑:程序博客网 时间:2024/05/29 23:43

   流的概念:

    在程序中所有的数据都是以流的方式进行传输或者保存的,程序需要数据的时候要使用输入流,程序要将一些数据保存的时候,就要使用输出流。

    程序中的输入输出都是以流的形式进行保存的,流中保存的实际上全都是字节文件。

字节流与字符流

 在java.io包中操作文件内容主要有两大类:字节流和字符流,两类都分别输入和输出操作。在字节流中输出数据主要使用OutputStream完成,输出使用InputStream在字符流中输  入主要用Reader完成,输出用Writer完成。(这四个都是抽象类)

操作流程

在java中io操作也是有相应的步骤的,以文件操作为例,文件的操作流程如下:

1.使用File类打开一个文件

2.通过字节流或字符流的子类,指定输出的位置

3.进行读/写操作

4.关闭输入/输出

字节流

字节流主要是操作byte类型数据,以byte数组为准,主要操作类就是OutputStream、InputStream

字节输出流:OutputStream

OutputStream是整个IO包中字节输出流的最大父类,OutputStream是抽象类,要想使用抽象类就必须先实例化这个抽象类的对象。

示例:使用OutputStream进行字节流的输出

public class Test1 {    public static void main(String[] args) throws IOException {        File file = new File("d:test.txt");        OutputStream os = new FileOutputStream(file,true);        String str = "Hello World";        byte[] b =str.getBytes();        os.write(b);        os.close();    }}
示例中使用了FileOutputStream中的构造方法:public FileOutputStream(File file,boolean append)throws FileNotFoundException,其中如果将boolean appen中的值设置为true,则表示在文件的末尾追加内容,否则每次写入将会覆盖文件的原内容。

字节输入流:InputStream

既然程序可以向文件中写入内容,则就可以通过InputStream从文件中把内容读取进来,首先看InputStream类的定义:

public abstract class InputStream extends Object implements Closeable

与OutputStream一样,InputStream也是抽象类,必须依靠其子类,如果现在是从文件中读取,就用FileInputStream来实现

观察FileINputStream类的构造方法:

public FileInputStream(File file)throws FileNotFoundException

示例:使用InputStream进行字节流的输入

public class Test1 {    public static void main(String[] args) throws IOException {        File file = new File("d:test.txt");        InputStream is = new FileInputStream(file);        byte [] b = new byte[(int) file.length()];        is.read(b);        is.close();        System.out.println(b.length);        System.out.println(new String(b));    }}
示例中开辟数组空间时,根据文件内容的长度开辟,这样可以合理的利用内存空间。

字符流

在程序中一个字符等于两个字节,那么Java提供了Reader、Writer两个专门操作字符流的类

字符输出流:Writer

Writer本身是一个字符流的输出类,此类的定义如下:

public abstract class Writer extends Object implements Appendable,Closeable,Flushable

此类本身也是一个抽象类,如果要使用此类,则肯定要使用其子类,此时如果向文件中写入类容,所以应该使用FileWriter的子类

FileWriter类的构造方法定义如下:

public FileWriter(File file)throws IOException

字符流的操作比字节流操作好在一点,就是可以直接输出字符串了,不用再像之前那样进行转换操作了

示例:写文件

public class Test1 {    public static void main(String[] args) throws IOException {        File file = new File("d:test.txt");        Writer out = new FileWriter(file);        String str = "Hello World";        out.write(str);        out.close();    }}
字符输入流:Reader





0 0
原创粉丝点击