2 个小例子,Java文件输入流 FileInputStream FileOutputStream你不可不懂,

Java中,字节流读取必不可少


看代码



public static void main(String[] args) {

//c盘已经包含两个txt文件,其中有一些字符串,可以自己建立
File file = new File("c://abc/bcd/123.txt");
File writeFile = new File("c://abc/bcd/234.txt");
try {
//字节流读取
FileInputStream fis = new FileInputStream(file);

//字节输出流
FileOutputStream fos = new FileOutputStream(writeFile,true);

//一个字符一个字符的去读取
//FileReader fileReader = new FileReader(file);
//一个字节一个字节的读取
// int length = fis.available();
// for(int i = 0 ;i<length;i++){
// int a = fis.read();
// System.out.println(a);
// }

//1024个字节读取
//ArrayList<Byte> listByte = new ArrayList<Byte>();
byte [] b = new byte[(int) file.length()];
while(fis.available()>0){
fis.read(b);


}

fos.write(b);
fos.flush();
fos.close();

//字符数组读取
// char [] msg = new char[1024];
// fileReader.read(msg);
// for(int i = 0 ;i<msg.length;i++){
// System.out.println(msg[i]);
// }

fis.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


这里是普通的文本读取



输入流,在实际开发中我们这样用,比较一下速度



//activity.rmvb是已经存在的一个500mb的视频文件,b.rmvb    java会自己建立

public static void main(String[] args) {
// TODO Auto-generated method stub


File readFile = new File("c:/abc/activity.rmvb");
File writeFile = new File("c:/abc/b.rmvb");
if(!writeFile.exists()){
try {
writeFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//f赋值的开始时间
long begin = System.currentTimeMillis();

try {   //此处需要抛出异常,初始化输入输出流
FileInputStream fis = new FileInputStream(readFile);

FileOutputStream fos = new FileOutputStream(writeFile,true);
//加入缓冲流,为了提高速度,可以把与buffer有管的语句删了,看看速度
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte b [] = new byte[1024];
while(bis.available()>0){
bis.read(b);
bos.write(b);
bos.flush();
}

//这里,先关bos,bis
bos.close();
bis.close();
fis.close();
fos.close();
//打印,总耗时
long end = System.currentTimeMillis();

System.out.println(end-begin);



//这里抛出异常的父类
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值