输入流输出流
流是一连串流动的字符或字节进行数据传递,是以先进先出(FIFo)方式发送信息的通道
需要数据转移,使用IO
分三步
1.确定数据传输类型,选择合适的流对象
2.调用对象方法
3.关闭
- 所有的流总共分为4类
在基本实现之外
缓冲流:Buffered+流
打印流:Print+流
转换流:OutputStreamWriter
对象流:Object+流(想把对象放入流中,这个对象的类,必须是实现序列化接口的)
3.同级资源调用的基本原则,先开后关
有包装关系的,先关外层,后关内层
1输入和输出 需要有参照物(内存)
输入流【文件到内存,ir 读入】input read
输出流【内存到文件 ow 写出】out write
文件:相关记录的数据放在一起的集合
文件存储位置:内存,光盘硬盘
访问方法:java.io,
2.创建文件对象
File f=new File(“文档名”)
参数还可以是,(url),或者(parent,child);
【文档是否存在 f.exists(); 】
是否是文件 f.isFile() 是否是目录 f.isDictionary();
文件位置:相对路径 f. getPath 绝P对路径f.getAbsolutePath()
文件名字:f.getName()
文件大小:file.length() 【字节大小】
是否创建文件:createNewFile();
删除文件:f.delete;
3文件的读写
package cn.kgc.tyl.test1012;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFileOutPutStream {
public static void main(String[] args) {
FileOutputStream fos=null;//因为有异常出现,所以先声明
try {
fos=new FileOutputStream("D:/唐元",true);
//文件写入默认覆盖原文件内容,参数默认false,可以省略,如果两个参数,设置为true,文件是追加。
String str="goodluck";
fos.write(str.getBytes());//把字符串转为byte类型
System.out.println("写入成功");
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
*写入成功
goodluck
* */
4.字节按行读取BufferedReader
内容较多,不需要一次性处理,或直接转换字符串
package cn.kgc.tyl.test1012;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
*
写文件,写出
* */
public class TestBufferedWriter {
public static void main(String[] args) {
BufferedWriter bw=null;
try {
bw=new BufferedWriter(new FileWriter("D:/唐元",true));//此行是FileWriter
//bw.write("march on");//int,char,String都可以 覆盖原内容
bw.append("666666");//追加字符串;
System.out.println("写入成功");
} catch (Exception e) {
e.printStackTrace();
}finally {
if (bw!=null) {
try {
bw.flush();//写入文件时清除缓存
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
*
第一次用write()文档内容是march on
第二次append()文档内容是march on666666
* */
*******