输入流就是把电脑磁盘中存储的东西输入到java代码中
package com.qf.a_fileinputstream;
import java.io.*;
public class Demo2 {
public static void main(String[] args) throws IOException {
//1.创建一个file对象的 文件抽象
File file = new File("c:/aaa/1.txt");
//2.创建字节输入流的核心的类
FileInputStream fis = new FileInputStream(file);
//3.加缓冲功能
BufferedInputStream bis = new BufferedInputStream(fis);
//4.创建一个数组 缓冲数组
byte[] buf = new byte[4 * 1024];//4096字节
/**
* 5.读取方法
* public int read(byte[] b) 将文件中的数据 读取到缓冲数组中
* throws IOException
* 从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
* 重写:
* read在 InputStream类
* 参数
* b - 读取数据的缓冲区。
* 结果
* 读入缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达, -1 。
*/
int length;
while ((length = bis.read(buf)) != -1) {
System.out.println(new String(buf, 0, length));
}
//6.关闭
bis.close();
fis.close();
}
}
输出流就是从java代码把文件输入到电脑磁盘中
package com.qf.b_fileoutputstream;
import java.io.*;
public class Demo1 {
public static void main(String[] args) throws IOException {
//1.创建文件对象
File file = new File("c:/aaa/2.txt");
//2.创建核心的字节输出流对象FileOutputStream
FileOutputStream fos = new FileOutputStream(file);
//3.加缓冲的效果 BufferedOutputStream
BufferedOutputStream bos = new BufferedOutputStream(fos);
//4.声明一个字符串
String str = "abcdefgh";
/**
* void write(byte[] b) 将字节数组中的数据写入到-
* 将 b.length个字节从指定的字节数组写入此文件输出流。
*/
//bos.write(str.getBytes());
/**
* void write(byte[] b, int off, int len)
* 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。
*/
//bos.write(str.getBytes(), 0, 3);
bos.write(1);
bos.close();
fos.close();
}
}