Java的IO_05四大抽象类及基本代码

本文深入讲解Java中的IO流概念,包括字节输入流与输出流、字符输入流与输出流的父类及其常用方法。通过两个示例代码,演示了如何使用FileInputStream进行文件读取,从创建源到选择流、操作数据直至释放资源的完整过程。
抽象类说明常用方法
InputStream字节输入流的父类,数据单位为字节。• int read() • void close()
OutputStream字节输出流的父类,数据单位为字节。• void write(int) • void flush() • void close()
Reader字符输入流的父类,数据单位为字符。• int read() • void close()
Writer字符输出流的父类,数据单位为字符。• void write(String) • void flush() • void close()

IO的操作步骤

  1. 创建源(搬那套房子)
  2. 选择流(选搬家公司)
  3. 操作(人还是卡车)
  4. 释放(打发搬家公司)
    基础版(即一个一个的读取字符):
package com.io.cx2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 理解操作步骤
 * 1创建源
 * 2选择流
 * 3操作
 * 4释放资源

 */
public class test1 {

	public static void main(String[] args) {
		//1、创建源
		File src = new File("text.txt");
		//2、选择流
		try {
			InputStream  is =new FileInputStream(src);
			//3、操作 (读取)
			int data1 = is.read();  //第一个数据w
			int data2  = is.read(); //第二个数据o
			int data3  = is.read(); //第三个数据s
			int data4  = is.read(); //不是数据,文件的末尾返回-1
			System.out.println((char)data1);
			System.out.println((char)data2);
			System.out.println((char)data3);
			System.out.println(data4);
			//4、释放资源
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

完整的IO版如下:

package com.io.cx2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class test2 {
	public static void main(String []args) {
		//1.创建源
		File src=new File("D:\\EclipsePlace\\IO\\src\\com\\io\\cx2\\text.txt");
		//2.选择流
		InputStream r=null;
		try {
			r=new FileInputStream(src);
			//3.操作
			int temp;
			while((temp=r.read())!=-1) {
				System.out.println((char)temp);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}finally {
			try {
				//4.释放资源
				if(null!=r)
				r.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
//建议第二个代码多写几遍,这是IO的基础代码
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值