Haven't handled the FileNotFoundException file in Java program? [duplicate] - java

This question already has an answer here:
Unreported exception java
(1 answer)
Closed 2 years ago.
I have some trouble finding the file in a java program in mac system.
import java.io.File;
import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
public class Data{
public static void main(String[] args){
File file = new File("/Users/project/test.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
In the same directory, when I typed this command Javac Data.java, it would give this error
I have read multiple similar posts on StackOverflow, but unfortunately, I couldn't find a solution.
Data.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner sc = new Scanner(file);
^
1 error
I have tried setting the file path like:
"./test.txt"
"test.txt"
"/text.txt"
But still, the same error would occur.
I don't know if this is relevant, but I can only run the java command in the terminal in the ~ directory, and all the above java files are in the ~ directory too.
Does anyone have any suggestions?

Your code is not throwing an exception. Your error message does not mean that the FileNotFoundException is thrown.
You have a compile time error.
Whenever you open a file, it must be like this:
try {
File file = new File("/Users/tianrongzhen/project/test.txt");
} catch (Exception e) {
// handle exception here
}
Or like this:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/tianrongzhen/project/test.txt");
// rest of your code
}
There are 2 kinds of exceptions: Checked and Unchecked.
A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.
For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException or FileNotFoundException.
There is a huge difference between the two ways to handle exceptions above.
First one catches and handles Exception internally, so the caller doesn't have to do any exception handling.
Second one throws Exception, so the caller needs to handle the Exception.
Based on the question you have asked here, I would recommend you to read up on the basics on exception handling. Here is one resource, but feel free to explore.

Related

How to Prevent IOException with the File Class [duplicate]

This question already has answers here:
Difference between java.lang.RuntimeException and java.lang.Exception
(12 answers)
Closed last month.
I've been trying to get an image to be saved as a BufferedImage in my program, but every time I try to set the file pathname it always results in an IOException error.
File grass = new File("C:\\\\Users\\user\\eclipse-workspace\\minecraft\\textures\\GRASS.png");
private final BufferedImage grassTexture = ImageIO.read(grass);
private final BufferedImage dirtTexture = ImageIO.read(new File("C:\\\\Users\\\\user\\\\eclipse-workspace\\\\minecraft\\\\textures\\\\DIRT.png"));
As you can see I tried a couple of different patterns of backslashes. ^
I use Eclipse for my IDE and it gave me this:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
at minecraft.MinecraftGame.<init>(MinecraftGame.java:28)
at minecraft.MinecraftGame.main(MinecraftGame.java:151)
How can I prevent this error from occurring?
Get used to the fact that computer programs may face problems at runtime.
That means that not everything will be going as smooth as a developer might believe in.
Exceptions are a way to report errors. Preventing them would mean making sure that no exception will ever occur. Good, that is the perfect case a developer might have dreamt of. Reality is different.
So the compiler just warns you (the developer) that you have not designed your code for the fact that something might have gone wrong. The magic is not to prevent an exception but to define what should happen in case one occurs.
One way to deal with (and done by many beginners) is to just catch the exception and forget about it. A much better way is to mark your method that it might throw an exception. If you do this it would mean your application terminates on any error. But the user would be aware of it. And as developer you could learn when to come up with better strategies.
So change lines that look like this:
public static void main(String[] args) {
into that:
public static void main(String[] args) throws Exception {
until you know better.

Opening a file FileNotFoundException with scanner in Java, Eclipse, Ubuntu

I'm trying to write a parser to a file called "x". I want to use scanner. I tryied to follow actions from a tutorial: https://www.youtube.com/watch?v=3RNYUKxAgmw.
package q;
import java.io.File;
import java.util.Scanner;
public class Parser {
public static void main(String [] args) {
Scanner x = new Scanner(new File("/home/x/eclipse-workspace/q/src/q/x.txt"));
String s=x.nextLine();
System.out.print(s);
}
}
The file that I want to open is called "x", its text file. We can see it in Package Explorer on left side. I clicked right on its properties. There is visible file locatization.
There appears FileNotFoundException as on the picture. I doesn't understand why this file cannot be opened.
[update] But I'm not sure if this is what
There appears FileNotFoundException as on the picture. I doesn't
understand why this file cannot be opened.
That's not what's happening. The error is in compilation time (the program has not executed, it doesn't know if the file -will- exist). The compiler is telling you "this method/constructor, according to its declaration, can throw an Exception (in this case: a FileNotFoundException ) at run time; you have not told me what to do in that case".
You really need to read about how Exceptions are treated in Java.
For a quick remedy, add a throws Exception to your main declaration. (Bear in mind: that is an awful thing to do if you don't really understand what are you doing)

Java: Nothing will read in this file

Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0

Creating an empty file in a directory

I am a new java student currently working on File I/O. My professor has asked us to create a very simple "DC universe" game using interfaces and classes and has asked us in the current lab I am working on, to create an instance of an object and then save the file to a directory in our C drive. My problem, is that even after all my constant 2 hours of digging through past topics I still cannot find a proper explanation as to how I create a directory and THEN create a file and write to a file in that directory because it appears whenever I run my code to not be able to do both tasks simultaneously. The code below also contains an error at the "Print Writer" line and asks to add a throw clause for "file not found exception"
Any and all help is vastly appreciated
package runtime;
import java.io.*;
import java.util.*;
import model.hero.*;
public class Gameplay {
public static void main(String[] args) {
File x = new File("C://prog24178//dcheroes.dat");
if(!x.exists()){
x.mkdir();
}
PrintWriter output = new PrintWriter(x);
// 1. Create a save file called dcheroes.dat in {$root}\prog24178
// 2. Create a hero
// 3. Save hero to file
}
}
Two errors I see:
x.mkdir() will try to create C:\prog24178\dcheroes.dat as a directory. Use x.getParent().mkdir() to create C:\prog24178.
the PrintWriter error is Java complaining about you not catching a potential error. Your code is fine, it's just Java being demanding. Surround your code with a try { ... } catch (FileNotFoundException ex) { ... } block. Every function call that could potentionally throw an Exception needs to have that exception caught, or the containing function needs to be marked to also be a potential source of the exception (and you can't do the latter on main).

What exception is thrown while creating a file in java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Filewrite {
public static void main(String args[]) {
try{
String content="This is my world";
File f=new File("D:/abc.txt");
}catch(IOException i) {
i.printStackTrace();
}
}
}
Compilation of the above code gives an error:
IO exception is never thrown by this corresponding try block.
What exception may be thrown while creating a file?
From Java Docs:
Throws:
NullPointerException - If the pathname argument is null
When you want to see what Exceptions are being thrown by a method (constructor in this case), you can search in Java Docs, or if you are using Eclipse IDE, put cursor over the method, and press F2.
IOException comes when
Signals that an I/O exception of some sort has occurred. This class is
the general class of exceptions produced by failed or interrupted I/O
operations.
in your code you are just creating a file object. It throws a NullPointerException if the path is null.
If you want to do any operations with that file like read, write etc... it throws FileNotFoundException and IOException
The error caused because your code block will never throw an IOException.
IOException will be thrown mostly when doing IO operations on files or other sources
Explanation
When ever you try to catch checked exception only which will never be thrown by your code in try block then compiler will always give you error of compilation.
In this case you are not performing any file operation(creation, reading, writing).
So your code will never throw any io exception which is checked exception.
You can't catch that exception which will never be thrown by your try block.
How To Fix
You can fix by removing io-exception from catch block then code will compile fine.

Categories

Resources