字节流
字节流呢就是可以将文字图片音频等文件,转成字节,进行数据传输。
分为两种
1.输入流 InputStream, 从文件到程序是输入流,可以用来读文件
2.输出流 OutputStream,从程序到文件是输出流,可以用来写文件
下面我们来看看其中的方法
// 创建流 并绑定写入的文件路径 写入时 系统会帮你创建文件
FileOutputStream fos = new FileOutputStream("xx/Desktop/Test/dongdong.txt");
// 写入方法
// 该方法是按ASCII码写入文件
fos.write(65);
fos.write(22);
fos.write(33);
// 利用字节数组写
byte[] b = {66, 68, 89};
// "longlong" 转成 字节数组写
byte[] bytes = "longlong".getBytes();
fos.write(bytes);
// 按偏移量写入数组的字符
fos.write(b, 1, 2);
// 关闭资源
fos.close();
然后是读取字节流的方法
// 读取文件
FileInputStream fis = new FileInputStream("xx/Desktop/Test/dongdong.txt");
// 读取方法一
// 一个一个字节读取 按照ASCII码读
int read = fis.read();
System.out.println((char)read);
read = fis.read();
System.out.println((char)read);
read = fis.read();
System.out.println((char)read);
read = fis.read();
System.out.println((char)read);
read = fis.read();
System.out.println((char)read);
read = fis.read();
// 当文件读取完毕时 返回-1
// 读取方法2
// 循环读取文件
int num = 0;
while ((num = fis.read()) != -1) {
System.out.println((char)num);
}
// 关闭资源
fis.close();
字符流
字符流呢用来读写文档的。
其下也有两种抽象类
Writer 写文档
Reader 读文档
方法如下
// 创建字符输出流
FileWriter fw = new FileWriter("xx/Desktop/Test/wl.txt");
// 写入文件
fw.write(65);
// 刷新(会将内容 写入文件中)
fw.flush();
char[] c = {'6', '7'};
fw.write(c);
fw.flush();
// 字符串直接写入 mac中换行 \n windows 换行 /r/n
fw.write("泗泾啊泗泾\n你什么时候才能成为CBD");
fw.flush();
// 关闭资源 关闭之前 系统会帮你刷新一下
fw.close();
然后是循环读取
FileReader fr = new FileReader("xx/Desktop/Test/wl.txt");
// 用数组读取
char[] b = new char[1024];
int len = 0;
while ((len = fr.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
fr.close();