InputStream类和OutputStream类

来源:互联网 发布:卖软件的网站 编辑:程序博客网 时间:2024/05/06 10:14

InputStream类

package com.mipo.file;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;/** * InputStream抽象类是表示字节输入流的所有类的超类,它以字节为单位从数据源中读取数据。 * FileInputStream是InputStream的子类。 * 文件流是指那些专门用于操作数据源中文件的流,主要有FileInputStream,FileOutputSteam,FileReader,FileWriter四个类。 * 1个汉字字符=2 byte(字节)=16 bit(位) * 1个英文字符=1 byte(字节)=8 bit(位) * @author Administrator * */public class TestInputStream {//在Unicode编码中,一个英文字符是用一个字节编码的,一个中文字符是用两个字节编码的,所以用字节流读取中文时会乱码。public static void main(String[] args) {FileInputStream fis = null;try {//第一步:创建一个链接到指定文件的FileInputStream对象fis = new FileInputStream("D:\\Personal\\Desktop\\IO\\File\\demo\\readme.txt");//fis = new FileInputStream(File f)亦可System.out.println("可读取的字节数:"+fis.available());//第二步:读数据,一次读取一个字节的数据,返回的是读到的字节int i = fis.read();while (i != -1) {//若遇到流的末尾,会返回-1System.out.print((char)i);i = fis.read(); //再读}//byte[] b = new byte[1000];//int i = fis.read(b);//从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。//for (byte d : b) {//foreach(元素类型   元素变量 : 对象集合或数组表达式)//System.out.println((char)d);//}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {//关闭输入流try {fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
OutputStream类

package com.mipo.file;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * OutputStream抽象类是表示字节输出流的所有类的超类,它以字节为单位向数据源写出数据 * FileOutputStream类是OutputStream的子类 * 一般来说,FileInputStream和FileOutputStream类用来操作二进制文件比较合适,如图片,声音,视频等 *  * IO流操作文件流程: * 1,创建连接到指定数据源的IO流对象。 * 2,利用IO流提供的方法进行数据的读取和写入。在整个操作过程中,都需要处理java.io.IOException异常。 *   另外,如果是向输出流写入数据,在写入操作完成后,调用flush()方法强制写出所有缓冲的数据。 * 3,操作完毕后,调用close()方法关闭该IO流对象。 * @author Administrator * */public class TestOutputStream {public static void main(String[] args) {FileOutputStream fos = null;try {//第一步:创建一个向指定文件名的文件中写入数据的FileOutputStream对象//第二个参数设置为true,表示使用追加模式添加字节fos = new FileOutputStream("D:\\Personal\\Desktop\\IO\\File\\demo\\readme.txt",true);//第二步:写数据fos.write('#');//用字符文件输出流往文件中写入的中文字符没有乱码,这是因为程序先把中文字符转成了字节数组然后再向文件中写//Windows操作系统的记事本程序在打开文本文件是能自动“认出”中文字符fos.write("hello,world!".getBytes());fos.write("你好".getBytes());//第三步:刷新输出流fos.flush();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (fos != null) {try {//第四步:关闭输出流fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}



1 0
原创粉丝点击