NullPointerException using getSystemResource(..) - java

I try building a texture class for LWJGL 3 in Java.
My loadTexture function looks like this:
public static Texture loadTexture(String filename) {
int id = -1;
try {
File texture = new File(filename);
if (!texture.exists()) {
System.err.println("File '" + filename + "' does not exist.");
return null;
}
// crash in following line
InputStream stream = ClassLoader.getSystemResource(filename).openStream();
PNGDecoder decoder = new PNGDecoder(stream);
// Some code between here
return new Texture(id, new Vector2i(decoder.getWidth(), decoder.getHeight()));
} catch (IOException e) {
e.printStackTrace();
return new Texture(id, new Vector2i());
}
}
The stacktrace is following:
Exception in thread "main" java.lang.NullPointerException
at org.citynopolisproject.graphics.Texture.loadTexture(Texture.java:49)
at org.citynopolisproject.Game.<init>(Game.java:30)
at org.citynopolisproject.Game.<init>(Game.java:33)
at org.citynopolisproject.Game.main(Game.java:188)
The location of the file is: citynopolisproject/res/splash.png and the source file of the Texture.java (if needed) is stored in citynopolisproject/src/org/citynopolisproject/graphics.
But I don't get why it crashes and throws a NPE.
You have any ideas?
Greetings

The issue (I suspsect) is that ClassLoader.getSystemResource(filename) is returning null. This could be because the file you are looking for is not on the classpath or because the classloader can't find the resource by the name you reference it.
In order to help we'd need to know more about the structure of your project. Where is this file you are looking for and is this being run in a Jar file?
You may need to look up more info on how to reference resources on the classpath. And remember that once you build the jar you wont be able to reference it with new File(filename) normally.
EDIT
You most likely do not want to bypass getting your resource from that classpath. If you are ever going to jar this program then you should be using something that will work even after it has been jarred.

Related

Specifying file path in java causes FileNotFoundException

This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.

What am i doing wrong with copying my file?

So I am trying to copy one file from one place to the other using the solution found here :
Copying files from one directory to another in Java
My code creates the new directory but cant seem to find the file ,even though the landedtitlesFile is pointing to the proper path and file. I always get my "blast" comment in case you were wondering if my program gets to the end of the method.
Thank you for your time and patience.
private File landedtitlesFile = new File("C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Crusader Kings II\\common\\landed_titles\\landed_titles.txt");
private String modPath = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking";
public void createCopyLandedTitles(Boolean vanilla){
if (vanilla == true) {
File dir = new File(modPath + "\\common\\landed_titles");
dir.mkdir();
try{
FileUtils.copyFile(landedtitlesFile,dir);
}
catch (IOException e ){
System.out.println("blast");
}
}
copyFile expects the second parameter to be the destination file, not a destination directory. You need to give it the target name of the file within that directory:
FileUtils.copyFile(
landedtitlesFile,
new File(dir, landedtitlesFile.getName());
Exception objects generally contain some information on the cause. If you print out the exception with e.printStackTrace(); (or rethrow it up the stack with throw new RuntimeException(e);) then you will be able to see what it says.

How to rename a file without making another file (Java)

I am looking for a away to rename a file to a string. renameTo only takes another file as a parameter, but I want it to take a string. So basically, how do I implement this method here?
public static void renameFile(File toBeRenamed, String new_name) {
}
I would like to rename the file "toBeRenamed" to "new_name". Do I have to make another file called new_name, or is there some workaround? Thanks!
EDIT: Thanks for the answer Luiggi. Here is a pic of the new error:
The File class doesn't represent the physic file in the hard drive, it is just an abstract representation. Creating a new instance of File class doesn't mean you are creating a physical file.
By knowing this, you can rename your file using a new File without worrying about creating new physical files. Code adapted from Rename a file using Java:
public static void renameFile(File toBeRenamed, String new_name)
throws IOException {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
throw new IOException("file exists");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}
EDIT: Based on your question update and on this comment:
I took a pic of the error. "Unhandled Exception Type IO Exception"
Looks one of these:
You don't know how to handle checked exceptions.
To do this, you should wrap the method that throws the Exception (or subclass) in a try-catch statement:
String new_name = getFilename(file);
try {
renameFiles(files[i], new_name);
} catch (IOException e) {
//handle the exception
//using a basic approach
e.printStacktrace();
}
More info: Java Tutorial. Lesson: Exceptions.
You don't want your method to throw a checked exception. In this case, it would be better to throw an unchecked exception instead, so you don't need to handle the exception manually. This can be done by throwing a new instance of RuntimeException or a subclass of this:
public static void renameFile(File toBeRenamed, String new_name) {
File fileWithNewName = new File(new_name);
if (fileWithNewName.exists()) {
throw new RuntimeException("file exists.");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}
More info in the link posted in the above section.
You don't want to throw an exception at all. In this case, it would be better to at least return a value to know if the file was exactly renamed:
public static boolean renameFile(File toBeRenamed, String new_name) {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
return false;
}
// Rename file (or directory)
return toBeRenamed.renameTo(fileWithNewName);
}
And update your code accordingly:
String new_name = getFilename(file);
boolean result = renameFiles(files[i], new_name);
if (!result) {
//the file couldn't be renamed
//notify user about this
System.out.println("File " + files[i].getName() + " couldn't be updated.");
}
Which one to choose? Will depend entirely on your taste. If I were you, I would use the third option for a quick dirty or learning phase work, but for a real world application I would use second option but using my own custom exception that extends from RuntimeException.
Perhaps this could be useful for you
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
if(file2.exists()) throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
This is extracted from a similar question Rename a file using Java

toRealPath(), IO/NIO package Java

I have just read on this tutorial that toRealPath(), should give back the absolute path if the file that the path refers to really exists.
Here is a snippet from the same tutorial:
try {
Path fp = path.toRealPath(); } catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
// Logic for case when file doesn't exist. } catch (IOException x) {
System.err.format("%s%n", x);
// Logic for sort of file error. }
So, now when I use an existing file located on my desktop for example (Path inputPath = Paths.get("/home/user/Desktop/indeed.txt"); It gives me an exception like if it did not exist.
What may cause this problem?
Thanks a lot in advance indeed.
EDIT: I get a NoSuchFileException out of it.
java.nio.file.NoSuchFileException: /home/user/Desktop/indeed.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixPath.toRealPath(UnixPath.java:833)
at Pathss.main(Pathss.java:25)
according the source of jdk, the translateToIOException method is implemented like this:
private IOException translateToIOException(String file, String other) {
// created with message rather than errno
if (msg != null)
return new IOException(msg);
// handle specific cases
if (errno() == UnixConstants.EACCES)
return new AccessDeniedException(file, other, null);
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
if (errno() == UnixConstants.EEXIST)
return new FileAlreadyExistsException(file, other, null);
// fallback to the more general exception
return new FileSystemException(file, other, errorString());
}
You can view the whole source at here http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/nio/fs/UnixException.java#86
According the implementation, when NoSuchFileException is throwed, an ENOENT error occured. ENOENT on unix stands for No such file or directory.
Are you sure file "/home/user/Desktop/indeed.txt" exsits? or you have privileges to access it.
What is the result of command ls -l /home/user/Desktop/indeed.txt
what is the version of jdk you are using?
Can you tell us the exact exception thrown? As tutorial you mentioned says:
This method throws an exception if the file does not exist or cannot be accessed.
So it may be that you simply cannot access that file.

Java formatter - setting file directory

i am trying to create a text file in a folder (called AMCData). The file is called "File" (for the sake of this example).
I have tried using this code:
public static void OpenFile(String filename)
{
try
{
f = new Formatter("AMCData/" + filename + ".txt");
}
catch(Exception e)
{
System.out.println("error present");
}
}
But before i get the chance to even place any text in it, the catch keeps being triggered..
Could anyone inform me why this is occuring?
more information:
The folder does not exist, i was hoping it would automatically create it
If it doesn't automatically create folders, could you please link me to how to do so?
You're right, a Formatter(String) constructor needs the file to be present or createable. The most likely reason why a file cannot be created is that it references a folder that itself doesn't exist, so you should use the File.mkdirs() method, like this:
new File("AMCData").mkdirs();

Categories

Resources