以下代码存在5处错误,请找出~~
package com;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ForTest {
public String cpoyFile(String type) throws IOException {
FileInputStream fis = null;
if ("1".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/1.txt");
} else if ("2".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/2.txt");
} else if ("3".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/3.txt");
}
FileOutputStream fos = new FileOutputStream("D:/WorkSpace9/4.txt");
int read = -1;
try {
while ((read = fis.read()) != -1) {
fos.write(read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
return "2";
}
fis.close();
fos.close();
return "0";
}
public static void main(String[] args) {
ForTest test = new ForTest();
try {
System.out.println(test.cpoyFile("2"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} --------------------编程问答-------------------- qing使用代码标签 --------------------编程问答--------------------
package com;--------------------编程问答-------------------- while ((read = fis.read()) != -1) { --------------------编程问答-------------------- 1.new FileInputStream("D:/WorkSpace9/1.txt");
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ForTest {
public String cpoyFile(String type) throws IOException {
FileInputStream fis = null;
if ("1".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/1.txt");
} else if ("2".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/2.txt");
} else if ("3".equals(type)) {
fis = new FileInputStream("D:/WorkSpace9/3.txt");
}
FileOutputStream fos = new FileOutputStream("D:/WorkSpace9/4.txt");
int read = -1;
try {
while ((read = fis.read()) != -1) {
fos.write(read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
return "2";
}
fis.close();
fos.close();
return "0";
}
public static void main(String[] args) {
ForTest test = new ForTest();
try {
System.out.println(test.cpoyFile("2"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.new FileInputStream("D:/WorkSpace9/2.txt");
3.new FileInputStream("D:/WorkSpace9/3.txt");
4.new FileOutputStream("D:/WorkSpace9/4.txt");
应该是new FileOutputStream("D:\\WorkSpace9\\4.txt");
试过new FileOutputStream("D:/WorkSpace9/4.txt"); 这样会报错。。 --------------------编程问答--------------------
这里没有问题,不会报错。
fis有空指针的可能
fis.close();fos.close();应该放在finally块里
FileNotFoundException 没有捕获或抛出 --------------------编程问答-------------------- --------------------编程问答-------------------- 1.当参数不是1,2,3 或者 1.txt,2.txt,3.txt不存在的时候 ,
fis.close();
fos.close();
会报空指针异常,应该在finally里面写,而且需要判空
2.方法也应该抛出FileNotFoundException 这个异常
3.你已经捕获了 IOException 那应该就不用再抛出了吧
我就想到了这3个~~ --------------------编程问答-------------------- 那个路径,和空指针
补充:Java , 非技术区