第一种:字节流FileInputStream FileOutputStream
1.1 读取操作
//先创建一个和硬盘连接的流(打通硬盘和内存的通道)
FileInputStream fis = new FileInputStream("D:\\Demo.txt");
//创建缓存区大小是1k
byte[] bytes = new byte[1024];
int data = 0; //存储有效字节数
StringBuffer sb = new StringBuffer();
//由于文件大小通常远远大于缓冲区大小,所以要循环读取
while((data = fis.read(bytes)) != -1){//返回-1则文件读取完毕,停止循环读取
String temp=new String(bytes,0,data);//读取缓冲区的字节数,转换成字符串
sb.append(temp);
System.out.printlb("====有效字节数===="+data);
}
System.out.printlb(sb.toString());
//关闭流
fis.close();
1.2 写入操作
//创建一个读取文件的流
FileOutputStream fos = new FileOutputStream("E:\\Demo.txt");
String temp = "海内存知己,天涯若比邻。";
//把字符串分解成字节,填到字节数组中
byte[] bytes = temp.getBytes();
//写入到指定路径,没有则创建文件
fos.write(bytes);
//关闭流
fos.close();
System.out.println("写入成功!");
第二种:字符流 char FileReader FileWriter
tips:在不同操作系统和编码方式下,char和byte之间的关系不是固定的
一般认为:gbk/gb2312 2个byte
utf-8 3个byte
2.1 读取操作
Reader fr = new FileReader("E:\\Demo.txt");char ch[] = new char[1024];
StringBuffer sbf= newStringBuffer();int length =fr.read(ch);while (length != -1) {
sbf.append(ch);
length=fr.read();
}
System.out.println(sbf.toString());
fr.close();
2.2 写入操作
Writer fr = new FileWriter("D:\\Demo.txt");
fr.write("有朋自远方来,不亦乐乎");
fr.close();
第三种:带缓冲区的字符读取和写入方案
BufferedReader
BufferedWriter 缓冲区 存储的数据量默认是1024byte
3.1 读取操作
Reader fr = new FileReader("D:\\Demo.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
fw.close();
3.2 写入操作
Writer fw = new FileWriter("D:\\Demo.txt",true);//true 为连续追加
BufferedWriter bw = new BufferedWriter(fw);
bw.write("学而时习之,不亦説乎");
bw.close();
fw.close();
第四种:二进制方式的读取和写入方案
DataInputStream
DataOutputStream
读写操作:复制粘贴
InputStream is = new FileInputStream("E:\\春暖花开.jpg");
DataInputStream dis = new DataInputStream(is);
OutputStream ops = new FileOutputStream("D:\\春暖花开.jpg");
DataOutputStream dos = new DataOutputStream(ops);
byte[] bytes = new byte[1024];
int date = 0;
while ((date = dis.read(bytes)) != -1) {
dos.write(bytes,0,date);
}
dos.close();
ops.close();
dis.close();
is.close();
System.out.println("复制成功");