Why won't my my catch block work? - java

I'm trying to test out the throws FileNotFoundException. At first, I placed my exec.txt in my project folder to test out my "testing" string & it works fine when I run my program.
But now, I removed my exec.txt file from my folder to see if the catch() part in the main method would work, but it doesn't. The File not found part of the catch() part won't appear in the console.
import java.io.*;
public class Crashable {
public static void openFile(String f) throws FileNotFoundException {
PrintWriter f1 = new PrintWriter(f);
f1.write("testing");
f1.close();
}
public static void main(String[] args) {
String f = "exec.txt";
try {
openFile(f);
} catch(FileNotFoundException e) {
System.out.println("File not found");
}
}
}

As stated in the documentation, an FileNotFoundException will be thrown when a file couldn't be accessed or created.
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
In your case it could create a new file, so no exceptions are thrown.

you can get it to throw the execption by trying creating the file in a non-existing dir:
String f = "zzz/exec.txt"

You never throw the exception in the openFile method. From the Java docs,
public PrintWriter(File file)
throws FileNotFoundException
Creates a new PrintWriter, without automatic line flushing, with the specified file. This convenience constructor creates the necessary
intermediate OutputStreamWriter, which will encode characters using
the default charset for this instance of the Java virtual machine.
Parameters:
file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
So if the file isn't there, you create a new file. So essentially, everything is working because although the file isn't there, when you create the PrintWriter object, it creates a new file, and doesn't throw the error.

You are actually creating a new file every time with this piece of code :
PrintWriter f1 = new PrintWriter(f);
f1.write("testing");
f1.close();
Instead try this :
public static void openFile(String f) throws FileNotFoundException {
File file = new File(f);
if(!file.exists())
{
throw new FileNotFoundException();
}
else
{
//do Something with the file
}}
Hope it helps..

Related

Unhandled exception type FileNotFoundException when trying to get a text file [duplicate]

Ive read a few threads here that relate the same problem, but the solutions arent working. :/
I use Eclipse, here is my program.
package mypackage;
import java.io.*;
public class myclass {
public static void main(String[] args) {
//String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
String myfile = "src/mypackage/myscript.abc";
File file1 = new File(myfile);
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
}
else{
log(myfile + " does not exist");
//System.exit(1);
}
//FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside
System.out.println("\nAbsPath : " + new File(".").getAbsolutePath());
System.out.println("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s){
System.out.println(s);
}
}
The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :
Unhandled exception type
FileNotFoundException myclass.java /myproject/src/mypackage
Wits end, pulling hairs.
Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws FileNotFoundException {
FileNotFoundException is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.
For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".
Use the file descriptor that you created and verified before creating the file reader. Also, you will probably run into problems using relative paths. Why is the line with the full path commented out? In any case, here is the code:
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
FileReader fr = new FileReader(file1);
}
I see that you tried to specify the full path to your file, but failed because of the following mistake:
you haven't declared or tried to catch java.io.FileNotFoundException.
To fix it, you can replace the line
FileReader fr = new FileReader("myscript.abc");
with the code:
try {
FileReader fr =
new FileReader("/home/jason/workspace/myproject/src/mypackage/myscript.abc");
} catch (FileNotFoundException ex) {
Logger.getLogger(myclass.class.getName()).log(Level.SEVERE, null, ex);
}
The following code is successfully compiled, and it should work:
package mypackage;
import java.io.*;
// It's better to use Camel style name for class name, for example: MyClass.
// In such a way it'll be easier to distinguish class name from variable name.
// This is common practice in Java.
public class myclass {
public static void main(String[] args) {
String myfile =
"/home/jason/workspace/myproject/src/mypackage/myscript.abc";
File file1 = new File(myfile);
if (file1.exists()) {
log("File " + myfile + " exists. length : " + myfile.length());
} else {
log("File " + myfile + " does not exist!");
}
try {
FileReader fr = new FileReader(myfile);
} catch (FileNotFoundException ex) {
// Do something with mistake or ignore
ex.printStackTrace();
}
log("\nAbsPath : " + new File(".").getAbsolutePath());
log("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s) {
System.out.println(s);
}
}
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws IOException{
}
You are expecting Eclipse to run the program in the project root directory. Unless you did something special with your "Run" configuration, I'd be suprised if it really starts there.
Try printing out your current working directory to make sure this is the right path.
Then try verifying that the bin / build directory contains your "*.abc" files, as they are not Java source files and may have not been copied into the compilation output directory.
Assuming that they are in the compliation directory, rewrite your file loader to use a relative path based on the class laoder's path. This will work well in exanded collections of .class files in directories (and later in packed JAR files).
Instead of trying to figure out what's going on, why not print what's going on...
Make this change to your code:
log(myfile.getName() + "(full path=" + myfile.getAbsolutePath() + ") does not exist");
You might find it either isn't using the directory you think, or (depending on your filesystem) it might be trying to create a file whose name is literally "src/mypackage/myscript.abc" - ie a filename with embedded slashes.
you can fix it simply declaring that throw this exception. Like this:
public static void main(String args[]) throws FileNotFoundException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}

Java-Selenium: Eclipse is unable to find my file, but my file is in its working directory

I am using Eclipse and the Java Library: java.io.FileInputStream;
My script cannot find a file that I want to assign to a variable using the constructor FileInputStream even though the file is in the Working directory.
Here is my code:
package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
public static void main(String [] args){
//verify what the working directory is
String curDir = System.getProperty("user.dir");
System.out.println("Working Directory is: "+curDir);
//verify the file is recognized within within the code
File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
} else {
System.out.println("File does not exist");
}
//Assign the file to src
File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
System.out.println("SRC is now: "+src);
//Get Absolute Path of the File
System.out.println(src.getAbsolutePath());
FileInputStream fis = new FileInputStream(src);
}*
My output is (when i comment out the last line) is
"Working Directory is: C:\Users\wes\workspace\QTI_crud
Yes, File does exist
SRC is now: C:\Users\wes\workspace\QTI_crud\values.xlsx
C:\Users\wes\workspace\QTI_crud\values.xlsx"
When I don't comment out the last line, I get the error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"
Where have I gone wrong in my code? I'm pretty new to Java
Much thanks!
Major problem with the code is that you after you know that file do not exist on specified directory, you tried to read the file. Hence, it is giving you the error.
Refactor it to this
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
try {
FileInputStream fis = new FileInputStream(f);
//perform operation on the file
System.out.println(f.getAbsolutePath());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
Here as you can see, if file exists then you try to read the file. If it is not available you don't do anything.

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.

Creating a simple data output file in Java

I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}

Detecting if args[0] is null or is not a text file

Can someone take a look at the code below and tell me why it isn't displaying an error message if args[0] is empty? The program works fine if the file entered is a duplicate, displaying the file already exists message. Java is throwing an ArrayIndexOutOfBounds error on me. I've tried adding that exception to the code as well but nothing is picking it up.
import java.io.*;
import java.util.*;
public class inputTest{
public static void main(String[] args) throws IOException{
if(args.length() == 0){
System.out.println("Please enter a correct text file name!");
System.exit(1);
}
java.io.File file = new java.io.File(args[0]);
if (file.exists()){
System.out.println("This file already exists!"); // If file exists, throw exception
System.exit(1);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
}
}
Also, is there a way to ensure the file being entered at the command prompt is of .txt variety?
This code will give comilation problem
Cannot invoke length() on the array type String[]
change to
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
if(args.length == 0){
System.out.println("Please enter a correct text file name!");
System.exit(1);
}
java.io.File file = new java.io.File(args[0]);
if (file.exists()){
System.out.println("This file already exists!"); // If file exists, throw exception
System.exit(1);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
}
Consider using Apache Commons ArrayUtils isEmpty() to test for emptiness of the Array without worrying about dealing with null array vs. empty array.
You can also use Apache Commons IO FilenameUtils getExtension() to get the extension of the file.
Though this won't help you master the concepts of Java, you may now become familiar with one of main sets of libraries used by Java devs, and with how to add libraries to your project.

Categories

Resources