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();
}
}