【发布时间】:2015-06-23 18:01:57
【问题描述】:
我有一个类PDF,它实现了一个接口fileReader。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class PDF implements fileReader {
@Override
public byte[] readFile(File pdfDoc) {
if (!pdfDoc.exists()) {
System.out.println("Could not find" + pdfDoc.getName() + " on the specified path");
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
}
import java.io.File;
public interface fileReader {
<T> T readFile(File fileObject);
}
我注意到变量 fin 存在范围问题。
我做的另一个实现是:
public byte[] readFile1(File pdfDoc) {
if (!pdfDoc.exists()) {
System.out.println("Could not find" + pdfDoc.getName() + " on the specified path");
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
return fileContent;
}
但现在我无法访问fileContent。
如何组合try-catches 以免出现范围问题?
有没有更好的设计方法来解决这个问题?我必须编写函数来读取三种不同类型的文件。
【问题讨论】:
-
您的范围问题究竟是什么?