最近,使用到了对zip文件进行解压,顺便整理了一下对文件流的处理,一起梳理一下,方便日后使用
首先来说对文件进行读取和复制是常见操作,先看一下一个简单实现
public static void copy(){
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(frompathname));//frompathname为需要复制的文件路径
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(topathname));//topathname为复制到的文件路径,目标文件应当与源文件格式一致,例 //如源文件为txt,则目标文件也应当为txt。例如formpathname=C:/aa.txt ,topathname=C:/bb.txt
byte[] buffer = new byte[1444];
int b;
while((b=bis.read(buffer))>-1){
bos.write(buffer,0,b);
}
bos.close();
bis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
对于应当使用字符流还是字节流进行读写操作的问题 ,如果为文本文件,则可以使用字符流进行读写,但是如果为图片等文件 则应当使用字节流进行读写,而且读写时候应当保持一致,即要么同时为字符流,要么同时为字节流
如果是zip文件直接复制同上类似,如果需要进行解压,则代码如下
public static void unzip() {
try {
/**此段代码不需要
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(new File("C:/3.7.zip")));
int b ;
byte[] tempbyte = new byte[8];
byte[] bytes = null;
byte[] temp = null;
try {
while ((b=bis.read(tempbyte, 0, tempbyte.length)) >-1) {
if(bytes==null){
bytes = new byte[tempbyte.length];
System.arraycopy(tempbyte, 0, bytes, 0, tempbyte.length);
}else{
temp = new byte[bytes.length+tempbyte.length];
System.arraycopy(bytes, 0, temp, 0, bytes.length);
System.arraycopy(tempbyte, 0, temp, bytes.length, tempbyte.length);
bytes = temp;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream ips = new ByteArrayInputStream(bytes);
*/
FileInputStream fis = new FileInputStream("C:/aa.zip");
ZipInputStream zis = new ZipInputStream(bis);//一定需要zipInputstream这个zip字节流,这个是关键,否则会当成一个文件处理
BufferedInputStream bbis = new BufferedInputStream(zis);
File Fout = null;
ZipEntry entry;
String Parent = "D:\\Desktop"; // 输出路径(文件夹目录)
try {
entry = zis.getNextEntry();
System.out.println("entry" + entry);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while ((entry = zis.getNextEntry()) != null
&& !entry.isDirectory()) {
Fout = new File(Parent, entry.getName());
if (!Fout.exists()) {
(new File(Fout.getParent())).mkdirs();
}
FileOutputStream out = new FileOutputStream(Fout);
BufferedOutputStream Bout = new BufferedOutputStream(out);
int bb;
while ((bb = bbis.read()) != -1) {
Bout.write(bb);
}
Bout.close();
out.close();
System.out.println(Fout + "解压成功");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(str);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
简单总结,便于以后使用