File is not found yet it is there - java

I was practicing reading text from a file and could not understand what I was doing wrong. This is what I had at first:
public class Main {
public static void main(String[] args){
File f = new File("C:\\test\\est.txt");
Scanner in = new Scanner(f);
while (in.hasNext()){
System.out.println(in.next());
}
}
}
The compiler said: Unhandled exception java.io.fileNotFoundException.
So I tried this:
File f = new File("C:\\test\\est.txt");
Scanner in = new Scanner(f);
try{
while (in.hasNext()){
System.out.println(in.next());
}
}catch (IOException i){
System.out.println(i.getMessage());
}
Now the compiler said: Unhandled exception java.io.fileNotFoundException. And also: java.io.fileNotFoundException is never thrown in the corresponding try block.
Then I tried this:
File f = new File("C:\\test\\est.txt");
Scanner in = new Scanner(f);
try{
while (in.hasNext()){
System.out.println(in.next());
}
}catch (IOException i){
throw new IOException(i.getMessage());
}
However it still says: Unhandled exception java.io.fileNotFoundException!
Can anyone please explain what I am doing wrong & how I can read all the text from a file in a manner that looks similar to my attempt.
**Note my file DOES exist.

An unhandled exception means that it might be thrown somewhere in your code, but you are not taking it into account when you explicitly have to. So to fix, wrap it in a try-catch:
File f = new File("C:\\test\\est.txt");
try
{
Scanner in = new Scanner(f);
while (in.hasNext()){
System.out.println(in.next());
}
}catch (IOException i){
e.printStackTrace();
}
Note that the Scanner is also inside the try block. Your attempt was good, but the Scanner constructor also might throw a FileNotFoundException. To fix such issues in the future, the compiler tells you exactly which line that throws the exception, not being handled.

Well the error tells you what the problem is ;-)
You are handling the IOException already, but not the FileNotFoundException!
Try like this:
File f = new File("C:\\test\\est.txt");
Scanner in = null;
try {
in = new Scanner(f);
} catch (IOException i){
i.printStackTrace();
}
while (in != null && in.hasNext()){
System.out.println(in.next());
}
edit: Ok actually FileNotFoundException extends IOException, so you don't need to handle it seperately obviously :)

You need to handle the FileNotFoundException by either saying:
throws FileNotFoundException
in your method header. Or adding a catch statement:
}catch (FileNotFoundException ex){
//log it or handle it
}
Also, avoiding throwing the same exception in the catch:
throw new IOException(i.getMessage());
So you want something like:
try{
File f = new File("C:\\test\\est.txt");
Scanner in = new Scanner(f);
while (in.hasNext()){
System.out.println(in.next());
}
}catch (FileNotFoundException ex){
//log it or handle it
}catch (IOException i){
//throw new IOException(i.getMessage());
//log it or handle it
}
Ok, but now the compiler prints java.io.FileNotFoundException:
C:\Users\Cristian\Desktop (Access is denied). Why is "Access denied?"
Make sure you have read access of that directory. Try running your IDE as administrator (you can do this by right-clicking on the IDE and click Run As Administrator).

Related

If a runtime exception was thrown after a resource was open - the program close the resource?

I wrote a simple java function that reads a file of Floating-point values and in the case file is not found or
the values that are being read are not floating-point the program throws exceptions.
My question is on the case that the program opened the file but the format of values was not floating-point - can the program close the resources? or should I consider the runtime exception that may happen?
public static ArrayList<Double> readValues(String filename) throws
FileNotFoundException {
var file = new File(filename);
var fileScanner = new Scanner(file);
var doubleList = new ArrayList<Double>();
//In case the values are not of double type and the scanner
while(fileScanner.hasNext())
doubleList.add( Double.parseDouble( fileScanner.next() ) );
fileScanner.close();
return doubleList;
}
o.k I updated the code to use in 'finally' statement
public static ArrayList<Double> readValues(String filename) throws
FileNotFoundException {
var file = new File(filename);
var fileScanner = new Scanner(file);
var doubleList = new ArrayList<Double>();
//In case the values are not of double type and the scanner
try {
while(fileScanner.hasNext())
doubleList.add( Double.parseDouble( fileScanner.next() ) );
}finally {
fileScanner.close();
}
return doubleList;
}
If there are better ideas, I would like to know.
Thanks for the help
Java finally block is always executed whether exception is handled or not.
Please refer to this
A standard approch
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(...);
// do something with the inputstream
} catch (IOException e) {
// handle an exception
} finally { // finally blocks are guaranteed to be executed
// close() can throw an IOException too, so we got to wrap that too
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
// handle an exception, or often we just ignore it
}
}
From java7: The try-with-resources Statement
From the oracle docs Refer here
You can close resources by using try with resources
try(// open resources here){
// use resources
} catch (FileNotFoundException e) {
// exception handling
}
// resources are closed as soon as try-catch block is executed.

I need to use a try-catch, but it says it is an unreachable catch block. How do I make it reachable?

I'm new to coding, and very new to java, so please bear with me, I'm sorry.
My professor says we need to use the following code as part of our assignment. I've looked through all my notes for the class, and I cannot find anything on try-catch and I'm not sure what I'm supposed to put in the insert code part or what the error message means
I'm very sorry, I'm just very confused. I keep getting
"Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
and I don't know how to fix it
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner( file );
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Edit: I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
What am I supposed to put in the try statement? I am so lost
I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException.
new Scanner(String) is not the same as new Scanner(File). If you look at the documentation, the first (using a String) reads from the string, not from a file. Since no file is involved, there's no FileNotFoundException.
If you want to hardcode the filename for testing purposes, do that in the new File(...) line, not the new Scanner(...) line:
try
{
File file = new File("cat.txt"); // <==== Here
Scanner scanner = new Scanner(file);
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
That will compile, because new Scanner(File) throws FileNotFoundException.
Welcome to SO! Exceptions are a great way to catch errors and decide how to handle them. Some segments of code require the program to take a leap and attempt to perform a task that may not be possible at that moment.
The errors specified in the question are a result of the Scanner not finding the file at the specified file path. The ArrayIndexOutOfBounds is indicating exactly what the exception states. The index being accessed is outside the bounds(size) of the array.
Java docs is a great resource and this should help clarify the purpose of catch statements.
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

Java I/O File Not Found

Currently trying to write a program to take input from a file and store it in an array. However, whenever I try to run the program the file cannot be found (despite file.exists() and file.canRead() returning true).
Here is my code:
public void getData (String fileName) throws FileNotFoundException
{
File file = new File (fileName);
System.out.println(file.exists());
System.out.println(file.canRead());
System.out.println(file.getPath());
Scanner fileScanner = new Scanner (new FileReader (file));
int entryCount = 0; // Store number of entries in file
// Count number of entries in file
while (fileScanner.nextLine() != null)
{
entryCount++;
}
dirArray = new Entry[entryCount]; //Create array large enough for entries
System.out.println(entryCount);
}
public static void main(String[] args)
{
ArrayDirectory testDirectory = new ArrayDirectory();
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
(In it's current state the method is only designed to count the number of lines and create the array)
The console output is as follows: true true c:/example.txt
The program seems to throw a 'FileNotFoundException' on the line where the scanner is instantiated.
One thing I have noticed when checking the 'file' object when debugging is although it's 'path' variable has the value "c:\example.txt", it's 'filePath' value is null. Not sure if this is relevant to the issue or not
EDIT: After Brendan Long's answer I have updated the 'catch' block. The stack trace reads as follows:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at assignment2.ArrayDirectory.getData(ArrayDirectory.java:138)
at assignment2.ArrayDirectory.main(ArrayDirectory.java:193)
Seemingly the scanner doesn't recognize the file and thus can't find the line
This code probably doesn't do what you want:
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
new FileNotFoundException("File not found");
}
If you catch any exception, you run the constructor for a FileNotFoundException and then throw it away. Try doing this:
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
ex.printStackTrace();
}
According to the javadoc for Scanner, nextLine() throws this exception when there is no more input. Your program seems to expect it to return null, but that's now how it works (unlike, say, BufferedReader which does return null at the end of the input). Use hasNextLine to make sure there's another line before using nextLine.

In Java, why am I getting a NullPointerException when trying to display a FileNotFoundException?

I think it's easier to just show the code and the output I'm getting than trying to explain it :)
This is from my main method:
//prompt user for filename
System.out.println("Please enter the text file name. (Example: file.txt):");
String filename = ""; //will be used to hold filename
//loop until user enters valid file name
valid = false;
while(!valid)
{
filename = in.next();
try
{
reader.checkIfValid(filename);
valid = true; //file exists and contains text
}
catch (Exception e)
{
System.out.println(e + "\nPlease try again.");
}
}
And this is the reader.checkIfValid method:
public void checkIfValid(String filename) throws InvalidFileException, FileNotFoundException
{
try
{
in = new Scanner(new File(filename));
if (!in.hasNextLine()) // can't read first line
throw new InvalidFileException("File contains no readable text.");
}
finally
{
in.close();
}
}
This is the output I get when a nonexistent file is entered:
Please enter the text file name. (Example: file.txt):
doesNotExist.txt
java.lang.NullPointerException
Please try again.
Why is the System.out.println(e) getting a NullPointerException? When I enter an empty file or a file with text, it works just fine. The empty file prints the InvalidFileException (a custom exception) message.
When I put a try-catch statement around the "in = new Scanner(new File(filename));", and have the catch block display the exception, I do get the FileNotFoundException printed out, followed by the NullPointerException (I'm not entirely sure why the catch block in the main method would be activated if the exception was already caught in the checkIfValid method...).
I've spent a while on this and I'm completely clueless as to what's wrong. Any help would be appreciated. Thanks!
edited: I think the null pointer comes from the call to reader, it is poor practise to catch all exceptions as you no longer know where they came from!
Maybe the checkIfValid method should just check if the filename is valid?
public boolean checkIfValid(String filename) {
try {
File file = new File(filename);
return file.exists();
} catch (FileNotFoundException) {
System.out.println("Invalid filename ["+filename+"] "+e);
}
}
Then the code calling it could look like;
filename = in.next();
valid = reader.checkIfValid(filename);
if (valid)
List<String> fileContents = readFromFile(filename);
Then contain all the file reading logic in it's own method like this;
public List<String> readFromFile(filename) {
List<String> fileContents = new ArrayList<String>();
try {
in = new Scanner(new File(filename));
while (in.hasNextLine()) {
fileContents.add(in.nextLine);
}
} catch (IOException e){
//do something with the exception
} finally {
in.close();
}
return fileContents;
}
My mistake was something only I could've seen. I was catching all the exceptions so I wasn't able to see where it was coming from. Thank you for helping!

Building a Scanner with an embedded FileReader recursively in java

public static Scanner getFileScanner()
{
try{
Scanner input = new Scanner(System.in);
String file = input.nextLine();
Scanner fs = new Scanner(new FileReader(file));
}catch (FileNotFoundException fe) {
System.out.println("Invalid filename. Try another:");
getFileScanner();
}finally{
return fs;
}
}
I keep getting the error that the variable fs isn't found. I can't figure out why for the life of me.
Your fs is declared under try block... to fix this, declare it outside the block:-
Scanner fs = null;
try {
...
fs = new Scanner(new FileReader(file));
}
catch (FileNotFoundException fe) {
...
}
finally {
return fs;
}
Variables declared inside a try block are not in scope inside the corresponding finally block. There are a number of issues with your approach in general... it's generally not a good idea to return inside a finally block, for example.
Here's what I'd do:
public static Scanner getFileScanner() {
Scanner input = new Scanner(System.in);
File file = null;
while (true) {
file = new File(input.nextLine());
if (file.exists() && file.isFile())
break;
System.out.println("Invalid filename. Try another:");
}
return new Scanner(new FileReader(file));
}
Lets start by listing the problems in your code:
The compilation error on the return statement is caused by fs being out of scope as described in other answers.
When you make the recursive call to getFileScanner(), you don't assign or return the result. So it won't make it back to the caller.
Using a return in a finally block is a bad idea. It will squash (throw away) any other exceptions that might be propagating at that point; e.g. exceptions that don't match a catch or exceptions thrown in a catch block.
The input.nextLine() call will throw an exception if the underlying stream has reached the EOF; e.g. the user typed [CONTROL]+D or whatever. You don't have to catch it (it is unchecked), but the return in the finally block squashes it (probably) resulting in the caller getting a null instead. Ughh ...
Hard-wiring System.in and System.out makes your method less reusable. (OK, this may not be an issue you should address in this particular case. And I won't, below ...)
In theory, your method could be made to throw a StackOverflowError; e.g. if the user hits [ENTER] a number of times. This problem is inherent in your recursive solution, and is a good reason not to do it that way.
Finally, here's a version of the method that addresses these problems:
public static Scanner getFileScanner() throws NoSuchElementException
{
Scanner input = new Scanner(System.in);
while (true) {
String file = input.nextLine();
try {
return new Scanner(new FileReader(file));
} catch (FileNotFoundException fe) {
System.out.println("Invalid filename. Try another:");
}
}
}
Note that I've replaced the recursion, gotten rid of the finally, and declared the exception that is thrown. (One could catch that exception and either report it, or rethrow it as an application specific exception.)
You declared fs in the try block and try to access it in a different scope (the finally block). The usual paradigms is to declare fs before the try block as null.
Declare it first:
public static Scanner getFileScanner() {
Scanner input = new Scanner(System.in);
Scanner fs = null;
while(fs == null) {
try{
String file = input.nextLine();
Scanner fs = new Scanner(new File(file));
}catch (FileNotFoundException fe) {
System.out.println("Invalid filename. Try another:");
}
}
return fs;
}
Just to expand on what the other guys indicated with their code samples...
Because you declare the fs variable within the try block the variable will only be scoped (visible) within the braces immediately after the try keyword.
By moving the fs variable declaration out of the try block and into the getFileScanner method body you are ensuring that the variable can be accessed by all blocks within the method body (try, catch and finally blocks).
Hope that helps!

Categories

Resources