Reputation: 394
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
Upvotes: 0
Views: 455
Reputation: 5399
I think this ClassLoader.getSystemResource("settings.txt")
code returns null and .getFile()
gets an NPE
Answer to comment
Firstly you should understand that method getSystemResource
NOT for outside resources read this
For load outside resources from jar you have to use full path to resource, full != absolute,
how to find full path
start point + path to resource
For example we have next files structure /Users/fakeuser/tetsproject/
- this folder contains your jar and conf
folder contains or should contain settings.txt
, if you have delivery structure like this your code will be
public static File file2 = new File("./conf/settings.txt");
And that is all.
Upvotes: 2