我认为不能以读字符串的方式来读ZIP文件,因为ZIP文件是二进制形式的,猜测FileReader读文件内容时碰到不符合字符编码的内容时会抛弃此部份内容,导致错误。
为什么不以字节流的形式读文件?JAVA里面提供了对ZIP文件的直接支持,可以查一下 java.util.zip.ZipInputStream 等类
为什么不以字节流的形式读文件?JAVA里面提供了对ZIP文件的直接支持,可以查一下 java.util.zip.ZipInputStream 等类
zipinputstream是可以,而且,我也用到了,我现在所做的东西是从别的地方传给我的一个经过压缩后的文件,到我这里就被处理成了一个压缩后的字符串了,我要用java.util.zip包来对这个字符串进行解压缩
public HashMap DecomByZip(String StrCompress)
{
ByteArrayInputStream bais=new ByteArrayInputStream(StrCompress.getBytes());
BufferedInputStream bis=new BufferedInputStream(bais,BUFFER);
ZipInputStream zip=new ZipInputStream(bis);
ZipEntry entry=null;
HashMap HashFile=new HashMap();
try
{
while ( (entry = zip.getNextEntry()) != null)
{
String name=entry.getName().toUpperCase();
System.out.println(name);
String strResult=null;
byte data[] = new byte[BUFFER];
int count;
while ((count = zip.read(data, 0, BUFFER))!= -1)
{
strResult+=new String(data,0,count);
}
HashFile.put(name,strResult);
}
zip.close(); }catch(Exception e)
{
System.out.println("Extract error!");
e.printStackTrace();
}
return HashFile;
}
import java.io.*;public class test
{
public static void main(String[] arg)
{
try
{
FileInputStream myReader = new FileInputStream("d:\\data.zip");
byte[] content = new byte[myReader.available()];
myReader.read(content);
FileOutputStream myWriter = new FileOutputStream("d:\\data_2.zip");
myWriter.write(content);
}
catch(Exception e) {}
}
}我测试过了,以字节流读出再写入不会有任何问题,两个文件完全一样。
你现在只是写测试程序,可以先把读byte[]参数的转换函数做好,如果非要用字符串做参数可以再想办法了。
import java.io.*;public class test2
{
public static void main(String[] arg)
{
try
{
FileReader myReader = new FileReader("d:\\data.zip");
int c;
String content = "";
while (-1 != (c = myReader.read())){
content += (char)c;
}
FileOutputStream myWriter = new FileOutputStream("d:\\data_2.zip");
myWriter.write(content.getBytes());
}
catch(Exception e) {}
}
}以字符串方式读出文件内容,结果目的文件与源文件内容不符,证明以Reader及其子类去读二进制文件会导致数据丢失。