Eventuali duplicati:
Java resource as fileTra cui un file di testo all'interno di un file jar e la lettura
Sono genere di nuovo a Java e sto cercando di ottenere un file di testo all'interno di una File jar
Nel momento in cui eseguo il mio jar, devo avere il mio file di testo nella stessa cartella del file jar. Se il file di testo non è presente, otterrò uno NullPointerException
, che voglio evitare.
Quello che voglio fare è ottenere il file txt all'interno del contenitore in modo da non avere questo problema. Ho provato alcune guide ma non sembravano funzionare. La mia funzione di lettura corrente è la seguente:
public static HashSet<String> readDictionary()
{
HashSet<String> toRet = new HashSet<>();
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Dictionary.txt");
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Read Lines
toRet.add(strLine);
}
}
return toRet;
}
catch (Exception e)
{//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return null;
}