1.1.1.字节流-操作文件基本演示
字节流可以处理的文件类型比字符流要多得多。字节流的顶层基类有InputStream、OutStream,所以以InputStream、OutStream为后缀的都是字节流。字节流与字符流是类似的,所以可以仿照字符流的流程写一下字节流的使用。
查看API,字节流中处理的是字节,这是它跟字符流最大的不同,字符流处理的是字符。
package com.java.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamDemo {
public static void main(String[] args) throws IOException {
demo_3();
}
private static void demo_1() throws FileNotFoundException, IOException {
FileOutputStream fos = new FileOutputStream("io.txt");
fos.write("abcde".getBytes());//这是跟字符输出流不一样,没有写输出,也没有flush,但是也能数据输出到文件,这是因为,字符流操作的是字符,字符在写出时需要转码,而字节流直接操作字符,所以不需要刷新
fos.close();
}
private static void demo_2() throws IOException {
FileInputStream fis = new FileInputStream("io.txt");
int ch = 0;
while ((ch = fis.read()) != -1) {
System.out.println((char) ch);
}
fis.close();
}
private static void demo_3() throws IOException {
FileInputStream fis = new FileInputStream("io.txt");
//建议使用这种读取数据的方式
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
fis.close();
}
}
1.1.2.字节流-练习-复制MP3
使用字节流可以处理更多类型的文件。现在使用字节流来复制MP3文件。
package com.java.base;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyMp3Test {
public static void main(String[] args) throws IOException {
copy_2();
}
public static void copy_1() throws IOException {
FileInputStream fis = new FileInputStream("D:\\视频\\笑傲江湖\\笑傲江湖01国语字幕DVD.mp3");
FileOutputStream fos = new FileOutputStream("F:\\大数据组件学习\\21.Java\\8.IO流\\bb.mp3");
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
fis.close();
}
public static void copy_2() throws IOException {
FileInputStream fis = new FileInputStream("D:\\视频\\笑傲江湖\\笑傲江湖01国语字幕DVD.mp3");
BufferedInputStream bufis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("F:\\大数据组件学习\\21.Java\\8.IO流\\bb.mp3");
BufferedOutputStream bufos = new BufferedOutputStream(fos);
int ch = 0;
while ((ch = bufis.read()) != -1) {
bufos.write(ch);
}
bufos.close();
bufis.close();
}
}