Reputation: 85
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt", "US-ASCII");
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException exception){
System.out.print("This is an IO Exception");
}
}
}
Output :- This is an IO Exception.
I am new to File Handling in Java. There are no errors in the program. It gives an IO Exception. Why is that?
Upvotes: 0
Views: 2083
Reputation: 1786
This code smells because you dont expose what actually going wrong, you hide information about exception and simple print "bad things happen" you need to print stack trace of your exception and you will be see what actually happen.
Perhaps you file doesn't exist yet, you need to create it before doing something with it, also pay attention how dou you create file, you need only path, before use something will be great to read javadocs File class javaodoc
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Upvotes: 0
Reputation: 131496
I don't know exactly the path where it is located your file but this is probably wrong :
File file = new File("FileHandlingExample1.txt", "US-ASCII");
It means your file US-ASCII
has as parent folder : FileHandlingExample1.txt
.
This is the File
constructor that you are using :
public File(String parent, String child)
You probably reversed the order of arguments.
And this statement :
FileWriter writer = new FileWriter(file);
throws an IOException if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
Upvotes: 1