FileNotFoundException when creating a Scanner in Eclipse with Java - java

I'm getting a FileNotFoundException when running the following Java 6 code on Eclipse (Indigo) on Snow Leopard:
import java.io.*;
import java.util.*;
public class readFile {
public static void main(String[] args) {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
}
The exception is
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at readFile.main(readFile.java:9)
My current workspace is /Users/daniel/pr/java. It contains only one project (readFile), and the file hierarchy looks like this:
- readFile
- src
- (default package)
- readFile.java
- JRE System Library [JavaSE-1.6]
- myfile.txt
After reading several very similar questions, I've tried
placing copies of myfile.txt in the project, bin, src, and workspace directories, as well as my home and root folders
identifying the working directory and using a relative path
manually setting the workspace via "Run Configurations > Arguments > Working Directory" in Eclipse
running the program with the command line Java launcher in the bin, readFile, src, and java directories (with copies of myfile.txt in all of these places)
removing the file extension and/or lengthening the filename (above some supposed minimum character limit), and
verifying the permissions of myfile.txt (they're now rw-r--r--).
I'm at a loss. What could be the problem? (Thank you for reading!)

The exception tells you the problem.
The code you have in your main might throw a FileNotFoundException, so you need to consider that in your code, either by declaring in the method signature that that exception can be thrown, or by surrounding the code with a try catch:
Declaring:
public static void main(String[] args) throws FileNotFoundException{
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
Or using try/catch
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch (FileNotFoundException e) {
//do something with e, or handle this case
}
}
The difference between these two approaches is that, since this is your main, if you declare it in the method signature, your program will throw the Exception and stop, giving you the stack trace.
If you use try/catch, you can handle this situation, either by logging the error, trying again, etc.
You might want to give a look at:
http://docs.oracle.com/javase/tutorial/essential/exceptions/ to learn about exception handling in Java, it'll be quite useful.

FileNotFoundException is a checked exception ! You must catch the exception ...
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch(FileNotFoundException ex) {
//Handle exception code ...
}
}

"/Users/daniel/pr/java/readFile/myfile.txt"
Shouldn't that be:
"/users/daniel/pr/java/readFile/myfile.txt"

Related

Java program gives me FileNotFoundException when the file I am reading from exists but then works perfectly fine if I handle the exception

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordJumble {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file = new File("F:/Files/Topic.txt");
Scanner sc = new Scanner(file);
String title = sc.nextLine();
System.out.println(title);
for(int i=0;i<10;i++){
System.out.println(sc.nextLine());
}
}
}
Currently the program does what I want it to, but why is it giving me an error about the file not existing? When I add the throws clause to ignore the error it is able to find the file without issue.
While the wording of the error may be a little confusing, the error isn't a FileNotFoundException in and of itself but is instead a complaint that you aren't dealing with the possibility of such an exception being thrown. All your compiler is telling you is that you need to deal with the possibility of the file not being where you think it is. Therefore, when you add throws FileNotFoundException to the method signature the compiler is satisfied and your error goes away.
When you said 'add the statement to ignore the error' you meant adding the 'throws...' clause to the definition of main so it would compile cleanly. Right?
What's going on is that Scanner many throw a FileNotFoundException if the file is not found. This exception must be handled (caught) somewhere.
Instead, you elected not to handle, and said that it could propagate out from main.
The appropriate way to do this is use a try - catch construction.
try {
Scanner sc = new Scanner(file);
:
:
catch (FileNotFoundException ex) {
... print an error or something ...
}
This sort of approach is used so that the error handling is 'out of line' of the main flow of the code.

Files.createSymbolicLink() (java.nio.file) doesn't override existing symbol link and doesn't throw exception

Based on the Java Doc, it will throw FileAlreadyExistsException if the link already exists. But in the actual testing, when running follow two lines, both of them return "/tmp/ln1" and no exception is thrown. And the "ln1" is still point to "/tmp/dir1". Seems this behavior doesn't follow the documentation. It's a JDK bug?
Is there a way to override the old link? like what's the command line does:
ln -nfs from to
Files.createSymbolicLink(Paths.get("/tmp/ln1"), Paths.get("/tmp/dir1"))
Files.createSymbolicLink(Paths.get("/tmp/ln1"), Paths.get("/tmp/dir2"))
I use JDK 1.7. The OS is Linux. I try those two statements, it creates a symbolic link according to the first statement, and then throws a FileAlreadyExistsException for executing the second one.
If you want to override the old link, you should delete the old link before you create a new link, like this:
public class Test {
public static void main(String[] args) throws IOException {
String link = "/tmp/ln1";
// create first symbolic link
deleteIfExists(link);
Files.createSymbolicLink(Paths.get(link), Paths.get("/tmp/dir1"));
//create second symbolic link
deleteIfExists(link);
Files.createSymbolicLink(Paths.get(link), Paths.get("/tmp/dir2"));
}
private static void deleteIfExists(String filePath) {
File file = new File(filePath);
if(file.exists()) {
file.delete();
}
}
}

Error with java FileInputStream and FileOutputStream

I just made my first I/O based stuff in Java.
I want to check if the content written to a file is properly saved in, or not.
For which i wrote the following code..
import java.io.*;
public class check implements Serializable {
//Make two variables and methods to initialise them
private int height;
private int width;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
public static void main(String[] args) {
check obj = new check();
obj.setHeight(20);
obj.setWidth(30);
try{
FileOutputStream fs = new FileOutputStream("foo.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(obj);
os.close();
}
catch(IOException ex){
}
//We set them to null so we can't access the objects on heap.
obj = null;
//Now we read them back from file
try{
ObjectInputStream is = new ObjectInputStream(new FileInputStream("foo.txt"));
check stored = (check) is.readObject();
//Check to see if it worked.
System.out.println("Variable, stored contains.." + stored.getType());
}
catch(IOException ex){
}
}
}
But it produces the following error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
at check.Check.main(Check.java:33)
Anyone got any idea to solve the issue?
Take a look at http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readObject(). The method lists a couple of exceptions. For every exception listed that is not a sub-class of RuntimeException you need to either catch the exception or declare that the method can throw that exception. You have only done this for IOException. You also need to do this for the other exceptions listed in the documentation. This needs to be done for all methods that throw non-runtime exceptions.
Your IDE is letting you run some code even though you are missing some classes or despite having compilation errors. Fix the compilation errors before you run them.
Your code is uncompilable at the moment. Line 36 fails.
System.out.println("Variable, stored contains.." + stored.getType());
This is because the class check does not contain a method getType(). Maybe You meant something along the lines of getClass().getName()?
Fix this error and try again. Your own error message does not make sense to me - is it generated by an IDE?
PS. Have a look at Java coding conventions regarding the naming of classes, variables and such. :)

NullPointerException without referencing any object

I have a piece of code, that throws NullPointerException sometimes. So far not really interesting. But the Exception occurs in a line, that does not reference any object.
try
{
parser.parse(input);/*line 186*/
}
catch(Exception e)
{
//NPE happens in the next line?
throw new SAXException("Error parsing document", e);/*line 190*/
}
Here the Stacktrace
java.lang.NullPointerException
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:190)
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:168)
....
It happened only twice in the last three months and the code run at least a hundred thousand times.
I already decompiled my code, to make sure the line information were correct and yes they are.
Additional Test
There seems to be something special with SAXException. I did the following test:
import org.xml.sax.SAXException;
public class Test
{
public static void main(String[] args) throws Exception
{
new SAXException("Error", new NullPointerException()).printStackTrace();
}
}
I got the following output
java.lang.NullPointerException
at Test.main(Test.java:7)
Caused by: java.lang.NullPointerException
... 1 more
Solution:
SAXException overrides toString method, to return the Name of the cause Exception.
Now I only wonder, that I did not get the caused by output in the production environment (AIX JAVA)
I wrote following code and generated null pointer exception. It came on line 45 as follow,
Exception in thread "main" java.lang.NullPointerException
at inheritance.parent.Child.main(Child.java:45)
import org.xml.sax.SAXException;
public class Child {
public static void main(String[] args) throws SAXException {
try{
Child c1 = null;
c1.i=0;
} catch(Exception e){
throw new SAXException("Error", e); //Line : 45
}
}
}
The error for your code is proper. You need to find which object you are getting null.
Your code must have changed since you made your last release. This will mess up the line numbers, since they are based on the code at the time it was compiled.
It looks like you've removed some code from that file since the release, meaning that the line numbers are larger than they should be.
Replace your line :
throw new SAXException("Error parsing document", e);
with
e.printStackTrace();
you will find the right error line.

reading filename through command line argument

I came across the following code in a book recently. It says that we can reference a file for instance that we want to read by writing a command line like the first line below. However it is throwing an error with this line. Can someone please advise as I have never come across this before?
Thanks
java ShowFile c:/Users/Bosra/Desktop/Sample.txt
import java.io.*;
public class ShowFile
{
public static void main(String args[])
{
int i;
FileInputStream fin;
//first confirm that a filename has been specified
if(args.length!=1)
{
System.out.println("Usage:ShowFile Filename");
return;
}
}
}
The first line is the thing you should type in at the command line after compiling the file - it doesn't belong in the file itself.

Categories

Resources