Java_136_IO_以程序为中心,程序读等于输入,程序写等于输出_节点流_处理流_四个抽象类_第一个程序:理解操作步骤

package IOStudy;

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

/**
 * 处理数据角度
 * 字节流:音频,视频,excel
 * 字符流:文本
 * 
 * 能使用字符流就能使用字节流,但能使用字节流不一定能使用字符流.
 * 
 * 以程序为中心,进来叫输入,出去叫输出
 * 
 * 节点流,处理流
 * 始终处于第一线的是节点流,为了提升性能我们包装叫做处理流,没有节点流处理流发挥不了任何的作用.
 * 
 * 节点流
 * ByteArray../File..
 * 
 * 处理流
 * DataInputStream/BufferedInputStream/Object..
 * 
 * 四个抽象类
 * 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()
 * 
 * Java虚拟机不直接对接文件,只能向操作系统进行申请
 * Java->OS->文件
 * Closeable方法通知操作系统可以关闭这个资源
 * 
 * OutputStream
 * Closeable释放资源,Flushable(手动刷新) 避免数据驻留在内存中
 * 
 * @author pmc
 */

/**
 * 第一个程序:理解操作步骤
 * 1.创建源
 * 2.选择流
 * 3.操作
 * 4.释放资源
 * @author pmc
 *
 */
public class IOAbsrtractTest2 {
	public static void main(String[] args){
		//1.创建源
		File src=new File("txt.txt");
		//2.选择流
		InputStream is=null;
		try {
			is=new FileInputStream(src);
			//3.操作
			int temp = 0;
			while((temp=is.read())!=-1){
				System.out.println((char)temp);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4.释放资源
			try {
				if(is!=null){//避免空指针异常
					is.close();	
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

自己写的(多实践)

package IOStudy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOAbsrtractTest4 {
	public static void main(String[] args){
		File src=new File("def.txt");
		InputStream in=null;
		OutputStream out=null;
		try{
			if(!src.exists()){
				boolean s=src.createNewFile();
				if(s){
					System.out.println("创建成功");
				}else{
					System.out.println("创建失败");
				}
			}else{
				System.out.println("文件以创建");
			}
			out=new FileOutputStream(src);
			out.write(107);
			out.flush();
			in=new FileInputStream(src);
			int temp=0;
			while((temp=in.read())!=-1){
				System.out.println((char)temp);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr_Pmc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值