Mam klasę PDF
, która implementuje interfejs fileReader
.Problemy z zakresem zmiennych podczas korzystania z try-catch w Javie
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);
}
Zauważyłem, że istnieją problemy zakres zmiennych fin
.
Kolejna realizacja zrobiłem było:
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;
}
Ale teraz nie może uzyskać dostępu fileContent
.
Jak mogę połączyć try-catches
, aby nie mieć problemów z zasięgiem? Czy istnieje lepsze podejście do projektowania tego problemu? Muszę tworzyć funkcje do czytania trzech różnych typów plików.
Jakie są dokładnie problemy z zasięgiem? –