package com.byte_stream;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class OutPutStreamDemo04 {
public static void main(String[] args) throws IOException {
//1.创建一个文件字节输出流管道与目标文件接通
File f = new File("file-io-app\\src\\out04.txt");
OutputStream os = new FileOutputStream(f); //可以自动生成文件,直接写路径 先清空之前的数据,写新数据进去
OutputStream os2 = new FileOutputStream(f,true); //追加数据
//2.写数据出去
//a.public void write(int a):写一个字节出去
os.write('a'); //a
os.write(98); //b,这里98没有加'',识别为ascii码
// os.write('徐'); //乱码,只写了中文的一个字节
os.write("\r\n".getBytes(StandardCharsets.UTF_8)); //换行 \r\n兼容性更强,能在linux中使用
//b.public void write(byte[] ,int pos ,int len):写一个字节数组的一部分出去
byte[] buffer = {'a', 97, 98, 99};
os.write(buffer);
byte[] buffer2 = "太皞".getBytes(StandardCharsets.UTF_8); //将中文转成字节
os.write(buffer2);
os.write("\r\n".getBytes(StandardCharsets.UTF_8)); //换行 \r\n兼容性更强,能在linux中使用
//c.public void write (byte[] buffer ,int pos ,int len):写一个字节数组的一部分出去
byte[] buffer3 = {'a', 97, 98, 99};
os.write(buffer3,0,3);
os.write("\r\n".getBytes(StandardCharsets.UTF_8)); //换行 \r\n兼容性更强,能在linux中使用
//写数据一定要刷新数据,不然很可能丢失数据
// os.flush(); //刷新数据后,流还可以继续使用
os.close(); //释放资源,包含了刷新!关闭后流不可以使用
}
}
文件拷贝
package com.byte_stream;
import java.io.*;
/**
* 目标:学会用字节流完成文件的复制(支持一切文件类型的复制)
*/
public class CopyDemo05 {
public static void main(String[] args) {
try {
//1.创建一个字节输入流管道与原视频接通
File f = new File("E:\\play\\donghua\\八尺大人怪谈-遭遇篇\\Hasshaku-sama1-engsub.mp4");
InputStream is = new FileInputStream(f);
//2.创建一个字节输出流管道与目标文件接通
OutputStream os = new FileOutputStream("D:\\newHassshaku_sama.mp4");
//3.定义一个字节数组来转移数据
byte[] buffer = new byte[1024];
int len; //记录读取的字节数
while((len =is.read(buffer))!=-1){
os.write(buffer,0,len);
}
System.out.println("复制完成了!");
//4.关闭流
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
字节输出流适合一切格式的文件拷贝,不适合读取中文输出