Txt-Datei in Java einbinden und einlesen?

2 Antworten

kavvon 
Fragesteller
 12.12.2018, 21:33

ClassLoader classLoader = getClass().getClassLoader();

File dateiTXT  = new File(classLoader.getResource("resources/Datum.txt").getFile());

Die Datei Datum.txt liegt in src -> resources. Ich bekomm aber ne NullPointerException!

0
regex9  12.12.2018, 22:11
@kavvon

Eine NullPointerException kann fliegen, wenn:

(...) the resource could not be found, a URL  could not be constructed to locate the resource, the resource is in a package that is not opened unconditionally, or access to the resource is denied by the security manager.

!

0

Der Ort, an dem die Datei liegt, muss dem Classpath bekannt sein.

Dann kannst Du diese über getResource bzw getResourceAsStream abfragen.

Ich empfehle, dass Du mit einem Maven Projekt arbeitest. Dann hast Du eine vordefinierte Projektordnerstruktur und die Resourcen liegen in /src/main/resources.

Woher ich das weiß:Studium / Ausbildung