字节流
1:基本操作与字符流类相同
2:但它不仅可以操作字符,还可以操作其他媒体文件。
3:例程
a:Copy一个Jpg文件。
public class Io21_1 {
public static void main(String[] args) throws IOException {
demo_read();
}
public static void demo_writer() throws IOException{
//1,创建字节输出流对象,用于操作文件。(把内存中的文字,输出到文件里面)
FileOutputStream fos=new FileOutputStream("E:\\Io\\io11.txt");
//2.写数据,直接写入到了目的地中。
fos.write("你好吗121".getBytes());
//fos.flush();
fos.close();//关闭资源动作要完成
}
public static void demo_read() throws IOException{
//1.创建一个读取流对象,和指定文件关联。
FileInputStream fis=new FileInputStream ("E:\\Io\\io11.txt");
//1.一次读取一个字节。
/* int ch=fis.read();
System.out.println(ch);*/
/* int ch=0;
while((ch=fis.read())!=-1){
System.out.println((char)ch);
}*/
//建议使用这种读取数据的方式
/**/ int len=0;
byte[] buf=new byte[1024];
while((len=fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
/* System.out.println(fis.available());//读取有多少个字节
byte[] buf=new byte[fis.available()];
fis.read(buf);
System.out.println(new String(buf));
fis.close();*/
}
}
IO流(字节流-练习-复制MP3)
public class Io22_1 {
public static void main(String[] args) throws IOException {
Copy_4();
}
//这种方式千万别用,效率太慢
private static void Copy_4() throws IOException {
FileInputStream fis=new FileInputStream("E:\\Io\\0.mp3");
FileOutputStream fos=new FileOutputStream("E:\\Io\\5.mp3");
int ch=0;
while((ch=fis.read())!=-1){
fos.write(ch);
}
fos.close();
fis.close();
}
//不建议使用,在处理大文件的时候,会内存溢出。
private static void Copy_3() throws IOException {
FileInputStream fis=new FileInputStream("E:\\Io\\0.mp3");
FileOutputStream fos=new FileOutputStream("E:\\Io\\4.mp3");
byte[] buf=new byte[fis.available()];//这里有可能内存溢出
fis.read(buf);
fos.write(buf);
fis.close();
fos.close();
}
private static void Copy_2() throws IOException {
FileInputStream fis=new FileInputStream("E:\\Io\\0.mp3");
BufferedInputStream bufis=new BufferedInputStream(fis);
FileOutputStream fos=new FileOutputStream("E:\\Io\\3.mp3");
BufferedOutputStream bufos=new BufferedOutputStream(fos);
int ch=0;
while((ch=bufis.read())!=-1){
bufos.write(ch);
bufos.flush();
}
bufis.close();
bufos.close();
}
private static void Copy_1() throws IOException {
FileInputStream fis=new FileInputStream("E:\\Io\\0.mp3"); //输入到内存中。输入流
FileOutputStream fos=new FileOutputStream("E:\\Io\\1.mp3");//从内存中输入到设备中。输出流
int len=0;
byte[] buf=new byte[1024];
while((len=fis.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();
fis.close();
}
}