初步认识字节输入流:
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {//编译时的异常
File file = new File("D:\\aaa\\1.txt");//1.先找到文件的位置
FileInputStream fileInputStream = new FileInputStream(file);//2.创建文件字节输入流的对象
//3.FileInputStream这个流不具有缓冲的效果,
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);// 需要使用BufferInputStream来缓冲
byte[] b = new byte[4 * 1024];
int read = bufferedInputStream.read(b);//4.使用字节缓冲流来操作1.txt
System.out.println(read);//5.读取到字节大小
System.out.println(new String(b));//借助String来打印一下
}
}
字节输出流:
import java.io.*;
public class Demo1 {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\aaa\\2.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
String str = "你哈还是";
byte[] bytes = str.getBytes();//字符串转换为byte型的数组
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();//没有实际的意义,可以不写
bufferedOutputStream.close();//在输入流中顺序不能反,先开的后关,后开的先关。在输出流中先开先关。
fileOutputStream.close();
}
}