字节流

字节流

字节流的父类(抽象类):

InputStream:字节输入流

1.public int read() {}

2.public int read (byte[] b) {}

3.public int read(byte[] b, int off, int len) {}

OutputStream:字节输出流

1.public void write(int n) {}

2.public void write(byte[] b) {}

3.public void write(byte[] b, int off, int len) {}

文件字节流

FileInputStream:

public int read(byte[] b)  //从流中读取多个字节,将读到内容存入b数组,返回实际读到的字节数;如果达到文件的尾部,则返回-1

eg : 

public class Demo01 {
public static void main(String[] args) throws IOException {
//1.创建FileInputStream,并指定文件路径
FileInputStream fis = new FileInputStream("g:\\aaa.txt");
//2.读取文件
byte[] buf = new byte[3];
int count = 0;
while((count = fis.read(buf))!=-1){
System.out.println(new String(buf,0,count));
}
//3.关闭
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("执行完毕");
}
}

FileOutputStream:

public void write(byte[] b)  //一次写多个字节,将b数组中所有字节,写入输出流

eg : 

public class Demo02 {
public static void main(String[] args) throws IOException {
//1.创建文件字节输出流对象
FileOutputStream fos = new FileOutputStream("g:\\bbb.txt",true);
//2.写入文件
//fos.write(97);
//fos.write('b');
//fos.write('c');
String string = "helloworld";
fos.write(string.getBytes());
//3.关闭
fos.close();
System.out.println("执行完毕");
}
}
/**
* 使用文件字节流实现文件的复制
* @author
*/
public class Demo03 {
public static void main(String[] args) throws IOException {
//1.创建流
//1.1文件字节输入流
FileInputStream fis = new FileInputStream("g:\\001.png");
//1.2文件字节输出流
FileOutputStream fos = new FileOutputStream("g:\\002.png");
//2.一边读,一边写
byte[] buf = new byte[1024];
int count = 0;
while((count = fis.read(buf))!=-1){
fos.write(buf,0,count);
}
//3.关闭
fis.close();
fos.close();
System.out.println("复制完毕");
}
}

字节缓冲流

缓冲流:BufferedInputStream/Buffered0utputStream

提高I0效率,减少访问磁盘的次数

数据存储在缓冲区中,flush是将缓存区的内容写入文件中,也可以直接close

eg : 

public class Demo04 {
public static void main(String[] args) throws IOException {
//1.创建BufferedInputStream
FileInputStream fis = new FileInputStream("g:\\aaa.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
//2.读取
/*int data = 0;
while((data = bis.read())!=-1){
System.out.print((char)data);
}*/
byte[] buf = new byte[1024];
int count = 0;
while((count = bis.read(buf))!=-1){
System.out.println(new String(buf,0,count));
}
//3.关闭
bis.close();
}
}
public class Demo05 {
public static void main(String[] args) throws IOException {
//1.创建字节输出缓冲流
FileOutputStream fos = new FileOutputStream("g:\\buffer.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
//2.写入文件
for (int i = 0; i < 10; i++) {
bos.write("helloworld\r\n".getBytes());//写入8K缓冲区
bos.flush();//刷新到硬盘
}
//3.关闭(内部调用flush)
bos.close();
}
}
posted @ 2021-03-15 17:19  星忄守候  阅读(106)  评论(0)    收藏  举报