首先:对java流进行分类:
输入输出流是相对于计算机内存来说的(对于程序员来说,是刚刚相反的。)
字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流
File类:
File file = new File( String pathname );
String pathname → 指的是存放文件的路径
如果这个路径不存在的话,将会报错,可以通过mkdir或者mkdirs进行创建
File类常用方法:
文件的读写:
- 文本文件的读写
- 用FileInputStream和FileOutputStream读写文本文件
- 用BufferedReader和BufferedWriter读写文本文件
- 二进制文件的读写
- 使用DataInputStream和DataOutputStream读写二进制文件
使用FileInputStream 读文本文件和使用FileOutputStream 写文本文件:
在写入文件的时候,查找到目标文件之后, 后边有两个参数,一个是目标文件存放的地址,后边需要填写boolean,来判断是否需要进行覆盖写进文件内部的内容,默认是false,true是不覆盖,累加。
这里读和写实际上是一样的,我进行详细的说明使用FileOutputStream 写文本文件,读文件参考写文件!!
public class Demo01 {
public static void test() throws Exception{
FileOutputStream in = null;
try {
in = new FileOutputStream("D:/aa.txt",true);//查找到目标文件,赋给in对象
String a = "我是大帅哥!!!";//编写准备写入的字符串
byte[] b = a.getBytes();//将字符串传编写为字节流,并传到b内
in.write(b);//写进目标文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (in!=null) {
in.close();//关闭数据流
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
复制文本文件(将a文件内的东西写进b文件内):
public class Demo01 {
public static void test() throws IOException{
FileInputStream in = null;//这里主要是通过二进制进行读写的
DataInputStream datain = null;//二进制缓冲区
FileOutputStream out = null;
DataOutputStream dataout = null;
try {
in = new FileInputStream("D:/aa.txt");//查找要去出文件内容的文件目标
datain = new DataInputStream(in);//将获取到的内容存放到缓冲区内
out = new FileOutputStream("D:/aa1.txt",true);//文件不存在的话,会自动创建一个文件!!!!!!!
dataout = new DataOutputStream(out);
byte[] a = new byte[1024];//创建一个字节数组,来进行存放每次进行读写的内容
int len = -1;
while ((len = datain.read(a))!=-1 ) {//将缓冲区内部的数据存放到a字节数组当中,如果内容过多了,分开多次进行传入
dataout.write(a);//将内容写入,目标文件内
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dataout.close();//清除缓冲区内的内容
out.close();
datain.close();//关闭 各种读写
in.close();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
test();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用字符流读写文件:
方法和上边复制文本类似,上边使用的是字节流,其中将
byte[] a = new byte[1024]
替换成
char ch[]=new char[1024]
以及使用FileReader方法去读取文件
就是变成了字符流
提高读写文件的效率:
使用FileWriter类与BufferedWriter类
其中:
- BufferedWriter类是Writer类的子类
- BufferedWriter类带有缓冲区