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();
}
}
}
}
}