数据的传输,可以看做是一种数据的流动, 以内存为基准, 流向内存是输入流,流出内存的是输出流。输入也叫读取,输出也叫写出
顶级父类们,都是抽象类:
输入流 输出流
字节流 字节输入流<br />InputStream 字节输出流<br />OutputStream
字符流 字符输入流<br />Reader 字符输出流<br />Writer
输出流的构造方法,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据(不想清空,在构造方法()里面加个逗号和true表示追加内容,不清空原来的数据)。
虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
.getBytes() 字符串转为字节数组
idea用的utf-8码表一个汉字3个字节,不是3的倍数乱码。gbk码表一个汉字2个字节
输入
队列
“整体”装read()方法
有数组读取到的内容存到数组,方法的返回值表示读取到的有效字节个数,
没数组读取到的内容存到read方法的返回值,
但是只要读不到都返回-1,就可以定义变量接收read方法的返回值,循环赋值判断不等于-1就可以一直读
套路:
int ch; while(()!=-1){//()当成一个整体,不要漏掉里面的()括号 }
字节流什么都能拷贝,但可能乱码
字符流一般不会乱码,但只能拷贝文本
用字符流打印到文件内容:
import java.io.*; public class Test08 { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("day19\a.txt"); FileWriter fw = new FileWriter("day19\b.txt"); int ch; while ((ch = fr.read()) != -1) { //写入内存 System.out.println((char)ch);//打印到文件内容,用字符流先写入到内存 fw.write(ch); //读取 } fw.close(); fr.close(); } }
四种拷贝方式:
import java.io.*; public class Test05 { public static void main(String[] args) throws Exception { //字节流一次读一个字节拷贝 FileInputStream fis = new FileInputStream("day19\a.txt"); //a.txt以存在,且有内容 FileOutputStream fos = new FileOutputStream("day18\b.txt"); int ch; while ((ch = fis.read()) != -1) { fos.write(ch); } fos.close(); fis.close(); //字节流一次读一个字节数组拷贝 FileInputStream fis2 = new FileInputStream("day19\c.txt"); //文件存在 FileOutputStream fos2 = new FileOutputStream("day19\d.txt"); int ch2; byte[] arr = new byte[3]; while ((ch2 = fis2.read(arr)) != -1) { fos2.write(arr, 0, ch2); } fos2.close(); fis2.close(); //字符一次读一个字符拷贝 FileReader fr = new FileReader("day19\aa.txt"); FileWriter fw = new FileWriter("day19\bb.txt"); int h; while ((h = fr.read()) != -1) { fw.write(h); } fw.close(); fr.close(); // //字符流一次读一个字符数组拷贝 FileReader fr2 = new FileReader("day19\cc.txt"); FileWriter fw2 = new FileWriter("day19\dd.txt"); int h2; char[] c = new char[3]; while ((h2 = fr2.read(c)) != -1) { fw2.write(c, 0, h2); } fw2.close(); fr2.close(); } }