I am trying to create a block that writes a file when the file doesn’t exsist, but it has turned into a Catch-22. The file doesn’t exist, so it can’t write the file so it can exsist. Here is my attempt:
if(!FileReadWrite.file2.exists())
FileReadWrite.fileWrite();
public static File file2 = new File("./settings.txt");
public static void fileWrite()
{
try
{
FileWriter fstream = new FileWriter(file2);
BufferedWriter out = new BufferedWriter(fstream);
String c = Byte.toString(Textures.a);
out.write(c);
out.close();
}catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fin = null;
try
{
fin = new FileInputStream(file2);
while ((ch = fin.read()) != -1)
{
strContent.append((char) ch);
}
fin.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
I am using Eclipse. The file is in the bin folder, but when I export it to a jar it is outside the jar folder.
Exception in thread "main" java.lang.ExceptionInInitializerError
at srcD.Main.<init>(Main.java:19) //(FileReadWrite.fileWrite())
at srcD.Main.main(Main.java:129) //(Make JFrame)
Caused by: java.lang.NullPointerException
at srcD.FileReadWrite.<clinit>(FileReadWrite.java:7) //(public file...)
... 2 more
I think this
ClassLoader.getSystemResource("settings.txt")code returns null and.getFile()gets anNPEAnswer to comment
Firstly you should understand that method
getSystemResourceNOT for outside resources read thisFor load outside resources from jar you have to use full path to resource, full != absolute,
how to find full path
For example we have next files structure
/Users/fakeuser/tetsproject/– this folder contains your jar andconffolder contains or should containsettings.txt, if you have delivery structure like this your code will beAnd that is all.