Netbeans: Try to load file but not found (Java) - java

I have every time the same problem when I'm trying to load files with Java in Netbeans (6.9).
It seems that the files aren't found. I get the error:
java.lang.NullPointerException
In this context:
File file = new File(this.getClass().getClassLoader().getResource("file.xml").getFile());
// or this also don't work
File file = new File("file.xml");
The file file.xml is in the same directory as the Main.java file.
How could I load this file?

This should work (it does for me):
String path = URLDecoder.decode(getClass().getResource("file.xml").getFile(), "UTF-8");
File f = new File(path);
If I understand the Javadocs correctly, this should be the same as using getClass().getClassloader().getResource() but in my experience it is different

I would suggest that you add a line so it says something along the lines (untested):
File f = new File(....);
System.out.println("f=" + f.getAbsolutePath());
// do stuff with f
This will tell you exactly where the file is expected to be and allow you to figure out what exactly is going on.

Sometimes you might need to add an extra / in front
File file = new File(this.getClass().getClassLoader().getResource("/file.xml").getFile());

Related

How to not hard-code a file path

I'd like to calculate the path of a file placed into Source Packages using this implementation:
URL pathSource = this.getClass().getResource("saveItem.xml");
When I try to create a new File like the code below:
File xmlFile = new File(pathSource.toString());
And I try to use it to create a document like this:
Document document = builder.parse(xmlFile);
This give me the java.io.FileNotFoundException.
How can I calculate the file path without hard-coding?
PS: I already used pathSource.getPath() but it doesn't work either.
I would like to use a similar implementation:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
PPS: The structure is the following:
You can't access a resource that inside a JAR file as a File instance. You can only get an InputStream to it.
As such, the following line
File xmlFile = new File(pathSource.toString());
won't work properly and when an attempt is made to read it later, a FileNotFoundException will be thrown.
Assuming you're trying to parse a XML file using DocumentBuilder, you can use the parse(InputStream) method:
try (InputStream stream = this.getClass().getResourceAsStream("saveItem.xml")) {
Document document = builder.parse(stream);
}
Short answer - saveItem.xml is not in the classpath.
If it is a web application, then file may be added to WEB-INF/classes folder.
Edit:
Try this.getClass().getResourceAsStream() too.
getClass().getResource("saveItem.xml");
looks for the file in the same package (which are directories when you look at the file system) as the class that getClass() returns.
Make sure the file is in there. Also make sure it's really in there when you run your code, there's a difference between your source folder and the target or bin folder where the compiled class files are placed.
Also check what pathSource.toString() contains.

Generate a file next to the jar file containing the code

I have a jar with my application that should create a file next to it. So in folder I will have this :
Source
|_ MyApplication.jar
|_ generatedFile.txt
Easy thing I thought... nope.. I am lost... I have a code like this:
URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().substring(0, location.getFile().lastIndexOf("/MyContext"));
File file = new File(fileName + ".txt");
File file1 = new File(path + "/MyFileName.txt");
File file2 = new File(path.substring(1) + "/MyFileName.txt");
I tried different combinations, googled alot and I am lost... if I get for example
file1.getPath();
file2.getAbsolutePath();
and so on, the paths are correct... but the file isn't generated... Only working case is the first one, but that is located inside the jar and I don't want that.
I also tried to moving the existing file outside using
Paths.move(...
but that hasn't helped me at all..
Can someone help me with this ? And explain to me why isn't the examples above working ? Thanks..
The call File file = new File("my path string"); just creates a Java File Object instance in memory. You need to write something to the actual file you are targeting. The simplest way to create an empty file is to call file.createNewFile().

java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder

Android writing to a CSV file via OpenCsv

I try to write to a Csv file via:
mFileWriter = new FileWriter(
"/sdcard/program/file");
mCsvWriter = new CSVWriter(mFileWriter);
At the moment it throws an exception that the file doesn't exist.
It's true that the file doesn't exist. What's the easiest way to create the file?
Does the FILE not exist, or the DIRECTORY it's supposed to go into?
If you want to create a directory structure, you can always do
File file = new File("/full/path/to/file");
file.mkdirs();
This will create any path leading up to this file that doesn't exist yet.
I suppose the missing quotes around your file name are a typo?

Getting file path in java

Is there a way for java program to determine its location in the file system?
You can use CodeSource#getLocation() for this. The CodeSource is available by ProtectionDomain#getCodeSource(). The ProtectionDomain in turn is available by Class#getProtectionDomain().
URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
File file = new File(location.getPath());
// ...
This returns the exact location of the Class in question.
Update: as per the comments, it's apparently already in the classpath. You can then just use ClassLoader#getResource() wherein you pass the root-package-relative path.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("filename.ext");
File file = new File(resource.getPath());
// ...
You can even get it as an InputStream using ClassLoader#getResourceAsStream().
InputStream input = classLoader.getResourceAsStream("filename.ext");
// ...
That's also the normal way of using packaged resources. If it's located inside a package, then use for example com/example/filename.ext instead.
For me this worked, when I knew what was the exact name of the file:
File f = new File("OutFile.txt");
System.out.println("f.getAbsolutePath() = " + f.getAbsolutePath());
Or there is this solution too: http://docs.oracle.com/javase/tutorial/essential/io/find.html
if you want to get the "working directory" for the currently running program, then just use:
new File("");

Categories

Resources