12.1(IO)

来源:互联网 发布:苍南法院拍卖淘宝网 编辑:程序博客网 时间:2024/05/16 10:59

IO流

常用类

1流的种类

  • 按方向分:输入流,输出流
  • 按类型分:字节流,字符流,转换流
  • 按操作方式分:节点流,过滤流


2基本使用方式

public class Test4write {/* * 流的读写操作 * 1,打开流 * 2,读取内容 * 3,写入内容 * 4,一定要关闭流 * */public static void main(String[] args) {File file = new File("E:/youxi/2.txt");//文件读取位置File file1 = new File("E:/youxi/1.txt");//文件写入位置FileInputStream fis = null;//文件输入流BufferedInputStream bis = null;//缓冲流FileOutputStream fos = null;//文件输出流BufferedOutputStream bos = null;//缓冲流//io流有异常全部放在try,catch中操作try {//1,打开流fis = new FileInputStream(file);//打开文件输入流bis = new BufferedInputStream(fis);//给文件输入流套上缓冲流fos = new FileOutputStream(file1);//打开文件输出流bos = new BufferedOutputStream(fos);//套上缓冲流//缓冲流可以提高效率//2 读取文件内容byte[] b = new byte[1024];//将读取的数据放在字节数组中int len = 0;//读取字节的长度//循环读取,将文件内容读取到byte数组中,如果读取的字节大于或等于就继续读取//没有读取到数据是会返回-1while((len=bis.read(b, 0, b.length))>=0){//用read带参数的方法//3写入文件bos.write(b, 0, b.length);//用write带参数的方法}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{//最后要分别关闭流//如果有缓冲流,直接关闭缓冲流就可以try {if(bis!=null) bis.close();//关闭输入流} catch (IOException e) {e.printStackTrace();}try {if(bos!=null) bos.close();//关闭输出流} catch (IOException e) {e.printStackTrace();}}}

数据流和字符流的操作方式与这都差不多


3转换流

public static void main(String[] args) {BufferedReader br = null;//字符读取缓冲流try {//读取标准输入流(标准输入流是字节流型的)//所以需要使用转换流InputStreamReaderbr = new BufferedReader(new InputStreamReader(System.in));//转换流的应用//循环读取String str = null;//存放读取的内容while((str=br.readLine())!=null){System.out.println(str);}} catch (IOException e) {e.printStackTrace();}finally {//最后记得关闭流try {if(br!=null)br.close();} catch (IOException e) {e.printStackTrace();}}}

4对象流

对象流可以存储对象,但是该对象类要实现Serializable接口

1存储的对象实现Serializable接口,如果有不需要存储的属性可以使用transient关键字

//对象一定要实现Serializable接口才能读写class Ts implements Serializable{int i;String str;//设置之后这个属性就不会被存储transient int z;public Ts(int i,String str) {this.i=i;this.str = str;}}
2对象流的操作
public static void main(String[] args) {//实例化对象Ts ts = new Ts(3, "asd");//File file = new File("E:/youxi/1.txt");ObjectOutputStream oos = null;//输出流ObjectInputStream ois = null;//输入流try {oos = new ObjectOutputStream(new FileOutputStream(file));//打开流ois = new ObjectInputStream(new FileInputStream(file));//写入文件oos.writeObject(ts);//读取Ts t = (Ts) ois.readObject();System.out.println(t);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}finally{try {if(oos!=null)oos.close();//关闭流} catch (IOException e) {e.printStackTrace();}try {if(ois!=null)ois.close();} catch (IOException e) {e.printStackTrace();}}}








0 0
原创粉丝点击