IO流中四类常用流

目录

一、字节流

二、字符流

三、缓冲流

四、转换流


一、字节流

注意: FileOutputStream(File file) 、 FileOutputStream(String name) 或FileOutputStream(File file, false)创建FileOutputStream对象时会创建一个新的空文件;如果使用FileOutputStream(File file, true)创建FileOutputStream对象,则只在第一次执行时创建一个新的空文件。

代码如下:

File a = new File("D:\\a.mp3");
File b = new File ("D:\\b.mp3");
FileInputStream inputStream = new FileInputStream(a);
FileOutputStream outputStream = new FileOutputStream(b);
byte [] car = new byte[1024];
int length = 0;
while ((length = inputStream.read(car))!=-1){
    outputStream.write(car,0,length);
}

二、字符流

注意: FileWriter (File file) 、 FileWriter (String fileName) 或FileWriter (File file, false)创建FileWriter对象时会创建一个新的空文件;如果使用FileWriter (File file, true)创建FileWriter对象,则只在第一次执行时创建一个新的空文件。


代码示例:

FileReader reader = new FileReader("D:\\1.txt");
FileWriter writer = new FileWriter("F:\\1.txt");
int data;
while ((data = reader.read())!=-1){
    writer.write(data);
}
writer.flush();
writer.close();
reader.close();

三、缓冲流

代码示例:

FileInputStream fileInputStream = new FileInputStream("D:\\1.mp3");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("f:\\1.mp3");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte [] car = new byte[1024];
int length = 0;
while ((length = bufferedInputStream.read(car))!=-1){
    bufferedOutputStream.write(car,0,length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
FileReader reader = new FileReader("D:\\1.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
FileWriter writer = new FileWriter("D:\\1.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer);
char [] car = new char[1024];
int length;
while ((length = bufferedReader.read(car))!=-1){
    System.out.println(11);
    bufferedWriter.write(car,0,length);
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();

四、转换流

字符文件可以使用字节流读取,字节流转换为字符流,解决字符流乱码现象

代码示例:

FileInputStream inputStream = new FileInputStream("D:\\1.txt");
InputStreamReader reader = new InputStreamReader(inputStream,"GBK");
FileOutputStream outputStream = new FileOutputStream("F:\\1.txt");
OutputStreamWriter writer = new OutputStreamWriter(outputStream,"GBK");
char [] car = new char[1024];
int length;
while ((length = reader.read(car))!=-1){
    System.out.println(11);
    writer.write(car,0,length);
}
writer.flush();
writer.close();
reader.close();

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值