解决不了的文件压缩问题!想了老半天了!请大家赐我力量!先谢大家了……
运行结果:请输入需要压缩的第1文件的文件名:
a.txt
Exception in thread "main"
java.lang.NullPointerException at Zip.zip(Zip.java:19)
at Main.main(Main.java:8)
是否还需要输入文件?yes/no
不知道怎么解决了请高手指点。。谢谢。。
源代码:
//功能函数
import java.io.*;
import java.util.zip.*;
public class Zip {
void zip() throws
IOException{
BufferedReader in1;
in1 = new BufferedReader(new InputStreamReader(System.in));
String cs = null;
String[] file;
int i = 0;
do {
System.out.println("请输入需要压缩的第"+(i+1)+"文件的文件名:");
file=new String[i+1];
file[i]=in1.readLine();
i++;
System.out.println("是否还需要输入文件?yes/no");
} while (cs.equals("yes"));
in1.close();
ZipOutputStream out1;
out1 = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("b.zip")));
for (int j = 0; j <file.length; j++) {
BufferedInputStream in2;
in2 = new BufferedInputStream(new FileInputStream(file[j]));
out1.putNextEntry(new ZipEntry(file[j]));
int c = 0;
while ((c = in2.read()) != -1) {
out1.write(c);
}
in2.close();
}
out1.close();
}
}
//主函数
import
java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Zip zp = new Zip();
zp.zip();
}
}
------解决方案--------------------你的:
do {
System.out.println("请输入需要压缩的第"+(i+1)+"文件的文件名:");
file=new String[i+1];file[i]=in1.readLine();
i++;
System.out.println("是否还需要输入文件?yes/no");
} while (cs.equals("yes"));
in1.close();
是不对的,
其实到循环结束,你只读到了最后一个文件,而且数组的前几项都是空的,
在后面压缩的时候肯定会包
空指针异常
------解决方案--------------------Java code
void zip() {
BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));
String[] file=null;
try {
System.out.print("请输入压缩包数量:");
int sum=Integer.parseInt(in1.readLine());
file = new String[sum];
int i = 0;
do {
System.out.println("请输入需要压缩的第"+(i+1)+"文件的文件名:");
file[i]=in1.readLine();
i++;
} while (i<=sum-1);
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if(null!=in1){
in1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ZipOutputStream out1 = null;
BufferedInputStream in2 = null;
try {
for (int j = 0; j <file.length; j++) {
out1 = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file[j]+j+"_b.zip")));
in2 = new BufferedInputStream(new FileInputStream(file[j]));
byte[] temp=new byte[in2.available()];
out1.putNextEntry(new ZipEntry(file[j]));
in2.read(temp);
out1.write(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if(null!=in2){
in2.close();
}
if(null!=out1){
out1.close();
}
System.out.println("文件另外压缩复制完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}