I have been asked to convert this code with a throw exception IF to a try/catch block. I have set it up but am not sure what to put in lieu of the word output so that it may run. I am not sure after reading the book and oracles info try/catch I see what needs to be done so the txt file will print. I will post code to be modified and then my change with try/catch. thanks for any help.
public class WriteData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
Here is the code changed for the Try/Catch
import java.io.FileNotFoundException;
public class WriteData {
public static void main(String[] args) {
java.io.File file = new java.io.File("scores.txt");
try {
output = new java.io.PrintWriter(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
You are instanciating two times output when it is not needed.
All treatment related to output should be done in the try block so it is not executed if an error happen and the stack is redirected to exception block.
The output should be in a finally block to make sure the file is closed whatever happen.
Doing these correction, your code shoud look like this :
import java.io.*;
public class WriteData {
public static void main(String[] args) {
File file = null;
PrintWriter output = null;
try
{
file = new File("scores.txt");
output = new PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
finally
{
//The output not be instanciated if scores.txt was not found.
if(output != null)
output.close();
}
}
}
In my opinion, this is the best way to handle your case.
try {
output = new java.io.PrintWriter(file); // output is not defined yet
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
// This one will throw the FileNotFoundException
java.io.PrintWriter output = new java.io.PrintWriter(file);
You can modify it like this
try {
java.io.PrintWriter output = new java.io.PrintWriter(file);
//rest of the code
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
For your error:
Remove the catch block for IoException from jean-François Savard's solution.
FileNotFoundException is a checked exception thrown by PrintWriter(). As a practice only catch the exceptions declared in API signature.
(In fact keeping any one block should work, as FileNotFoundException extends IOException )
Related
So I have a working ObjectOutputStream in a method that I start by calling the method in main. I need to then read the file it created and print out all 5 objects in it. Right now I'm only printing out the first object.
public static AccountSerializable serializReadObject() throws ClassNotFoundException, IOException {
AccountSerializable read = null;
try { // Create an input stream for file accounts.ser
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
read = (AccountSerializable) input.readObject();
input.close();
} catch (IOException i) {
throw i;
}catch(ClassNotFoundException c){
throw c;
}
return read;
}
public static void main(String[] args) {
try {
System.out.println(serializReadObject());
} catch (ClassNotFoundException | IOException e) {
System.out.println("Class not found");
e.printStackTrace();
}
}
I've tried to throw
boolean eof = false;
while(!eof){
try{
//read data
}catch(EOFException e){
eof = true;
}
}
in serializReadObject To loop it and I've also tried to instead catch it in main but I keep getting an error stating "Unreachable catch block for EOFException it is already handled by the catch block"
I then tried to take away the IOException and just put EOFEception but alas it keeps forcing me to surround my read with IOException. Is there another way to loop this with EOF?
You're only getting the first object because your opening and closing the stream on each call. There are many ways to achieve what you want. One way is to use a List<AccountSerializable>:
public static List<AccountSerializable> serializeReadObjects() throws IOException, ClassNotFoundException {
// create an input stream for file accounts.ser
// this line will throw an IOException if something goes wrong
// we don't need to catch it in this method though
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
// create list to hold read in accounts
List<AccountSerializable> accounts = new ArrayList<>();
// keep reading until EOFException is thrown
boolean keepReading = true;
while(keepReading) {
try {
// read in serialized account
AccountSerializable read = (AccountSerializable) input.readObject();
// add read in serialized account to the list
accounts.add(read);
} catch(EOFException eofe) {
// we are at the end of file, so stop reading
keepReading = false;
input.close();
} catch(IOException ioe) {
// input stream error other than EOF, not sure what to do
input.close();
throw ioe;
} catch(ClassNotFoundException cnfe) {
// not sure what to do in this case, so close input
input.close();
throw cnfe;
}
}
return accounts;
}
public static void main(String[] args) {
List<AccountSerializable> accounts = null;
try {
// get list of read in accounts
accounts = serializeReadObjects();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
// iterate over list of read in accounts and output them to stdout
for(AccountSerializable account : accounts) {
System.out.println(account);
}
}
In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.
public class deleteFile {
public static void main(String args[]){
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append("c:/");
fileNameStr.append("Test");
File file = new File(fileNameStr.toString());
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
}
According to this code, when I get SQLException, it can't delete file. Why?
There is nothing special about deleting a file in a catch block.
If your code (above) is not deleting the file, then it could be a number of things:
You may have the file pathname incorrect.
The file may not exist in the first place.
Your application may not have permission to delete the file, due to normal file / directory permission issues, "mandatory access control" restrictions (e.g. SELinux) or Java sandbox restrictions.
The file may be undeletable because it is "in use" ... on Windows.
That particular exception may not be being thrown.
Your catch block with SqlException never catching.
Use finally{} block in order to delete file or free resource.
Actually my full source code is,
public class deleteFile {
public static void main(String args[]){
-------------------------
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append(.....);
fileNameStr.append(.....);
File file = new File(fileNameStr.toString());
PrintWriter printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),
"windows-31j")));
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
Finally I found the solution that is need to close printWriter before deletion file. Thank you for your advice.
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
printWriter.flush();
printWriter.close();
file.delete();}
}
I have a valet class method that should write an hourly wage to a file:
public void hourlyOverall() throws FileNotFoundException
{
PrintWriter out = new PrintWriter("wage info");
new FileOutputStream("wage info", true);
hourlyOverall = tips / hours + hourlyWage;
out.println(hourlyOverall);
}
However, when I run valet.hourlyOverall() in my main method, the file "wage info" is created but nothing is written to it. What am I doing wrong?
First of all use try-catch for Exception handling and then in the finally block close the OutputStream
out.flush();
Somthing like this
try {
PrintWriter out = new PrintWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
out.flush();
}
I think this is another way to solve your problem, but using another classes
public class valet {
public static void main(String []args)throws IOException
{
try
{
hourlyOverall()
}
catch(IOException ex)
{
System.out.println(ex+"\n");
}
}
public void hourlyOverall() throws IOException
{
FileWriter out = new FileWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.write(hourlyOverall+"\r\n");
out.close();
}
}
You probably shouldn't declare an anonymous FileOutputStream and you should probably close your PrintWriter,
PrintWriter out=new PrintWriter("wage info");
// new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
out.close(); // <-- like that
Do something like this (if java7 or above) :
public void hourlyOverall()
{
try (PrintWriter out=new PrintWriter("wage info")){
//new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
I'm using FileOutputStream with PrintStream like this:
class PrintStreamDemo {
public static void main(String args[]) {
FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
ps = new PrintStream(out);
ps.println ("This data is written to a file:");
System.err.println ("Write successfully");
ps.close();
}
catch (Exception e) {
System.err.println ("Error in writing to file");
}
}
}
I'm closing only the PrintStream. Do I need to also close the FileOutputStream (out.close();)?
No, you only need to close the outermost stream. It will delegate all the way to the wrapped streams.
However, your code contains one conceptual failure, the close should happen in finally, otherwise it's never closed when the code throws an exception between opening and closing.
E.g.
public static void main(String args[]) throws IOException {
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream("myfile.txt"));
ps.println("This data is written to a file:");
System.out.println("Write successfully");
} catch (IOException e) {
System.err.println("Error in writing to file");
throw e;
} finally {
if (ps != null) ps.close();
}
}
(note that I changed the code to throw the exception so that you understand the reason of the problem, the exception namely contains detailed information about the cause of the problem)
Or, when you're already on Java 7, then you can also make use of ARM (Automatic Resource Management; also known as try-with-resources) so that you don't need to close anything yourself:
public static void main(String args[]) throws IOException {
try (PrintStream ps = new PrintStream(new FileOutputStream("myfile.txt"))) {
ps.println("This data is written to a file:");
System.out.println("Write successfully");
} catch (IOException e) {
System.err.println("Error in writing to file");
throw e;
}
}
No , here is implementation of PrintStream's close() method:
public void close() {
synchronized (this) {
if (! closing) {
closing = true;
try {
textOut.close();
out.close();
}
catch (IOException x) {
trouble = true;
}
textOut = null;
charOut = null;
out = null;
}
}
You can see out.close(); which closes output stream.
No you dont need to. PrintStream.close method automatically closes the underlining output stream.
Check the API.
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#close%28%29
No, according to the javadoc, the close method will close the underlying stream for you.
No. It is not require to close other components. when you close stream it automatically close other related component.