FileInputStream is not found even though the file exists [duplicate] - java

This question already has answers here:
Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
(7 answers)
Unhandled exception: FileNotFoundException
(5 answers)
Closed 5 years ago.
I am trying to integrate Firebase with my Java Spring web application what runs on server and it give an error:
Unhandled exception: java.io.FileNotFoundException"
The file is exists in the directory:
FileInputStream serviceAccount = new FileInputStream("C:\Users\My Name\Downloads\Projectname\words.txt");
I run a bunch of prints when I just used File where it exists, its readable, the full file path or whatever is the exact same as the file path in the FileInputStream but nothing is working. i cant use a try catch because Firebase doesn't allow it or something. At this point I don't know what to do.

As mentioned in the proposed duplicate, it's likely that your problem is that you need to declare the possible exception by adding throws FileNotFoundException to your method (and all methods that call it). See Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
The code that you posted above also gives an error illegal escape character at compile time (because backslash is used in Java for representing special characters such as newline \n), which seems to be unrelated to the current problem, but you can fix it by replacing each single backslash with two backslashes as follows:
FileInputStream serviceAccount = new FileInputStream("C:\\Users\\My Name\\Downloads\\Projectname\\words.txt");

When you use path separator, you must remember use \ or / correctly. You should change it to
"C:/Users/My Name/Downloads/Projectname/words.txt"
in Java program.

Related

What is causing this ClassLoader- and File-related NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm creating a method that is supposed to find the path to a text file and return it as a String to be used for a configuration file. Here's the block of code that is being affected:
public String getConfigLocation() {
String fileName = "locateconfig.txt";
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
locationFile = file.getAbsolutePath();
return locationFile;
}
The line that's causing this exception to be thrown is File file = new File(classLoader.getResource(fileName).getFile());.
Here's the first few lines of the stack trace - just the first few, because all the methods being affected here interact with the one I'm having a problem with.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at epicorexpert.EpicoreJFrame.getConfigLocation(EpicoreJFrame.java:1068)
at epicorexpert.EpicoreJFrame.checkConfig(EpicoreJFrame.java:1076)
at epicorexpert.EpicoreJFrame.<init>(EpicoreJFrame.java:94)
What probably-obvious issue am I overlooking? Thanks.
Edit: Why is this being marked as a duplicate question and suggesting a redirect for the thread on what NullPointerExceptions are? I understand what they are and how they're typically resolved. That's not what I'm asking here; this is specifically about the ClassLoader and File objects and why I'm getting NPEs from them.
getResource returns null if the file is not found! That's most probably the cause of your NullPointerException!

Can't find file error handling [duplicate]

This question already has answers here:
How to Check Path is existing or not in java?
(3 answers)
Closed 7 years ago.
Is there a particular way on how to handle errors if my FileInputStream cannot find the inputted file name in its directory? I'm just trying to make it so if my program can't find the file that was typed it'd print an error stating "file doesn't exist"
EDIT: Left out info. Hoping to let users reinput the file name.
Should be as simple as this
try {
<your code>
} catch(FileNotFoundException e) {
e.printStackTrace();
}
The catch does not end your program, you can easily put a loop around the whole block and try it with a different file name each time.
Nevertheless it would be better to test if the file exists, before you try to open it.
new File("filename").exits()

close, destructor and finalize: Java contradictions [duplicate]

This question already has answers here:
Why does a Try/Catch block create new variable scope?
(5 answers)
Closed 8 years ago.
I have the following code, which works nicely in my class reading a file line by line.
try { FileInputStream in = new FileInputStream(filename);
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String line;
while((line=reader.readLine())!=null){
// read the file
}
}
catch (Exception e) {
System.out.println(e);
}
But if I try to add the command close, for after the file was finished reading, then I got the error:
in.close();
Error:(131, 9) java: cannot find symbol
symbol: variable in
location: class ReadFile
I searched about cleaning objects after use and the need to close files before your program ends. And found several posts on this for Java, but many are very contradictory. The point is that in the end I just get very confused.
Am I wrong, or Java programming is a little bit fuzzy and messy? I mean, there is apparently no real use of destructor, the use of finalize is very questionable, and the use of close is also suggested as unnecessary. Some of the posts on these issues are contradictory and non-conclusive.
So, how to proceed here? In the case I really need to close the file, how to get rid of this error message? Is it really dispensable and unnecessary to close files? What about cleaning up class instances for the the program finishes?
You are getting the error because you have defined variable in inside the try block, so it is not visible in catch/finally/or anywhere outside that try. Move the declaration outside try:
Change this
try { FileInputStream in = new FileInputStream(filename);
to
FileInputStream in = null;
try { in = new FileInputStream(filename);
you may be closing in.close() out side try block so obviously you will get error because in is defined in try block which is local.
Better to use try with resource so you need not to manually close file stream
Ideally you must call the close() method inside the finally block, after the null check.
And for that you need to declare the variable in outside the try block.
Calling the close() method in finally block ensures that it is called irrespective of whether an Exception is thrown or not by the code in try block.
EDIT : This is when you are using Java 6 or earlier version. For Java 7 and higher you could use try with resource as suggested by #JqueryLearner

Delete a file name with spaces in between

i read on several posts that we for deleting a file through java which has spaces in the name, i can use delete() method (Java 6). eg:
File f = new File("/mnt/test ex.txt");
f.delete();
but when I'm making a file object like this () :
StringBuilder fullFileName = "C:/Temp_Folder\week month.xlsx";
fileToRead = new File(fullFileName.toString());
fileToRead.delete();
I'm not able to do so and i get the following exception :
java.io.FileNotFoundException: "C:\Temp_Folder\week month.xlsx" (The filename, directory name, or volume label syntax is incorrect)
What am i missing here?
P.s. : I tried using quotes on the filename as well without success
fileToRead = new File('"'+fullFileName.toString()+'"');
Edit : I've edited the quotes on the stringBuilder (a type from my end). Actually the StringBuilder object is a parameter and we are appending objects to fetch the actual name. I just gave you the final declaration.
As far as week month.xlsx goes, that is the name of the file and not two different variables (which means the filename DOES have spaces in between; it could be something like
Name with spaces.xlsx
Thanks for the quick turnaround everyone.
You do NOT need a specific treatment for file names with spaces in Java -- or any other programming language with a file access API for that matter.
Do not mix Java with a command interpreter.
In your case, your File should be declared as:
new File("C:\\Temp_Folder\\name with spaces.xlsx")
and that's it.
If Java reports a FileNotFoundException then there is a problem. Unfortunately, the File API is broken and this exception can be thrown if the file exists but you cannot read it, for instance. Have a look at the complete stack trace.
Do yourself a favour: use Java 7 and the new Files API. With this API, exceptions actually make some sense -- and a delete operation will not "silently" fail either.
As to building the filename itself, you can for example use String.format():
final String filename = String.format("C:\\Temp_Folder\\%s %s.xlsx", month, week);
According to the exception:
java.io.FileNotFoundException: "C:\Temp_Folder\week month.xlsx"
You are looking for the following file:
"C:\Temp_Folder\week month.xlsx"
Note the quotes! This file does not exist.
You will have to modify your code to ensure that your file name does not include the surrounding quotes (not needed).
I.e. (Assuming java 6 here)
File file = new File("C:\\Temp_Folder\\week month.xlsx");
file.delete();
Note, the backslash is an escape character hence it is doubled in the string.

Java FileNotFoundException even though file exists

I am trying to read a file located at "C:\Users\Siddharth\Documents\aarti\yeh_vidhi_mangal.txt". Following code indicates that file exists
String filename = "C:\\Users\\Siddharth\\Documents\\aarti\\yeh_vidhi_mangal.txt";
File file = new File(filename);
System.out.println(file.exists());
but when I try to open the file using
FileInputStream in = new FileInputStream(file);
a FileNotFoundException is thrown. Is this because access is denied? I checked file permissions and they are fine.
I have also tried working without eclipse. from the command line:
C:\Users\Siddharth\workspace\file_io_test\src>javac Foo.java
Foo.java:16: error: unreported exception FileNotFoundException; must be caught o
r declared to be thrown
FileInputStream in = new FileInputStream(file);
^
1 error
According to the documentation for FileInputStream, "If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown." (emphasis mine) The file may be locked or in use by another application.
What does file.canRead() return?
Now that you've updated your question with more data, I can see that you are misinterpreting the error message. The error is that you are calling a method which throws a certain type of exception and you are not properly reporting or handling the exception. You can either add a try / catch for FileNotFoundException or add a throws to your method declaration which states that FileNotFoundException can be thrown.
Try using single slash rather than double slash like
C:/User/Documents/your Filename.
and use Backward Slash Because your File is going to inherit in the following Directories so
write the path like this for ex:
C:\User\Documents\Your Filename.

Categories

Resources