{% note info simple %}
字节流三步走:
- 创建字节输出流对象
- 写数据
- 释放资源
{% endnote %}
换行符
windows:\r\n
linux:\n
mac:\r
字节流写数据的三种方式
java
void write(int b); //以此写一个字节数据
void write(byte[]b); // 一次写一个字节数组数据
void write(byte[]b,int off,int len); //一次写一个字节数组的部分数据
读取文件案例
java
/**
* 简单的读取文件流程
* @throws IOException
*/
private static void readFile() throws IOException {
// 读取文件
FileInputStream fis = new FileInputStream("p:/test/a.txt");
int cha; // 定义每次读取的内容存放介质
while ((cha = fis.read())!=-1){
//输出内容
System.out.println((char)cha);
}
//释放资源
fis.close();
}
复制文件
简单复制
java
private static void copyFile() throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("./a.txt");
FileInputStream fileInputStream = new FileInputStream("v:/study/a.txt");
int b ;
while ((b = fileInputStream.read())!=-1){
fileOutputStream.write(b);
}
fileInputStream.close();
fileOutputStream.close();
}
使用byte[]提高复制效率
java
/**
* 利用字节数组提高复制效率
* @throws IOException
*/
private static void copymedia() throws IOException {
FileOutputStream fos = new FileOutputStream("./a.mp4");
FileInputStream fis = new FileInputStream("P:\\Study\\self-study\\Java\\2阶段二:JavaSE进阶\\第二章 2-Stream & IO\\0-1 Stream\\01-Stream流-初体验.mp4");
byte [] bytes = new byte[1024];
int len;
while((len = fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fis.close();
fos.close();
}
使用字节缓冲byte[]
java
private static void copyBufferArr() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new BufferedInputStream(new FileInputStream("P:\\Study\\self-study\\Java\\2阶段二:JavaSE进阶\\第二章 2-Stream & IO\\0-1 Stream\\01-Stream流-初体验.mp4")));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("./copy.mp4"));
byte [] bytes= new byte[1024];
int len;
while ((len = bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
}
小结
字节流:
可以操作(拷贝)所有类型的文件
字节缓冲流:
可以提高效率
不能直接操作文件,需要传递字节流
拷贝文件的四种方式:
- 字节流一次读写一个字节
- 字节流一次读写一个字节数组
- 字节缓冲流一次操作一个字节
- 字符缓冲流一次操作一个字节数组
本文是原创文章,采用 CC BY-NC-SA 4.0 协议,完整转载请注明来自 小码同学
评论
隐私政策
0/500
滚动到此处加载评论...

