IO流
输入流:
input :场景使用 从磁盘的d:/aaa/1.txt文件中 读取数据 到内存中(Java代码)
字节输入流
字符输入流
从内存写入数据到磁盘
输出流:
output :从内存写入到磁盘的d:/aaa/1.txt文件中
字节输入流
字符输入流
输入输出以内存为参照物体
字节输入流
FileInputStream
将磁盘上面文件的内容读取到Java代码中
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();
}
}
字节输出流
FileOutputStream
将Java代码中的一个字符串 写入到磁盘的一个文件中
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();
}
}
c:/bbb下面有一个视频文件 复制到c:/aaa下面
思路:先从磁盘读取到内存缓冲数组(输入流)中然后再写入磁盘中(输出)
public class Demo1 {
public static void main(String[] args) throws IOException {
copyVideo1();
}
public static void copyVideo () throws IOException {
//创建缓冲输入流对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("c:/bbb/12转义字符.mp4")));
//创建缓冲输出流对象
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("c:/aaa/sb.mp4")));
//准备一个缓冲数组
byte[] buf = new byte[4096];
int length;
while ((length = bis.read(buf)) != -1) {//length = bis.read(buf) 从磁盘读取数据到缓冲数组中
bos.write(buf, 0, length);//从缓冲数组中写入到磁盘
}
bos.close();
bis.close();
}
//不带缓冲的
public static void copyVideo1 () throws IOException {
FileInputStream fis = new FileInputStream(new File("c:/bbb/12转义字符.mp4"));
FileOutputStream fos = new FileOutputStream(new File("c:/aaa/2b.mp4"));
int length;
while ((length = fis.read()) != -1) {
fos.write(length);
}
fos.close();
fis.close();
}
}