Ho una classe PDF
che implementa un'interfaccia fileReader
.Problemi nell'ambito delle variabili durante l'utilizzo di try-catch in Java
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);
}
Ho notato che ci sono problemi di ambito per le variabili fin
.
Un'altra implementazione ho fatto è stato:
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;
}
Ma ora non ho potuto accedere fileContent
.
Come è possibile combinare lo try-catches
in modo da non avere problemi di ambito? Può esserci un approccio di progettazione migliore a questo problema? Devo fare funzioni per leggere tre diversi tipi di file.
Quali sono esattamente i problemi del tuo ambito? –