Is there any usage for nested try if without catch? - java

Came across the below code from a Java book
public void writeFile(String fileName, String content){
File file = new File(fileName);
try {
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
}
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
Nothing is wrong with the above code, I simply couldn't see the point of having a nested try that doesn't define an inner catch block. Or is there any purpose of doing so in which I've missed it?
Revised code:
public void writeFile(String fileName, String content){
File file = new File(fileName);
try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
output.println(content);
output.println();
output.println("End of writing");
System.out.println("File been written successfully");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}

The inner try is a try-with-resources:
try (PrintWriter output = new PrintWriter(new FileWriter(file)))
it means, that it manages the resource - PrintWriter - opens it and closes it after every statement in this try is conducted. The outer try is used to catch the error.
Your revised code what Petter Friberg proposed, is equivalent.

Related

How to solve failure to close a FileStream

I have closed file steam in try/finally, but code analysis warns me:
Possible failure to close a FileOutputStream
Possible failure to close a PrintWriter
Possible failure to close an OutputStreamWriter
How can failure happen? How can I ensure the FileStream is closed?
public void writeFile(String filepath)
{
BufferedWriter bw = null;
PrintWriter pw = null;
try {
File file = new File(filepath);
bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
pw = new PrintWriter(bfw);
//do something
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
bfw.close();
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
If you are using Java-7 and above then you can use try with resources
File file = new File(filepath);
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
PrintWriter pw = new PrintWriter(bfw);)
{
...
}
catch(Exception exception) //This is optional
{
exception.printStackTrace();
}
You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.
Hope this helps!
How can failure happen?
See your finally block:
finally{
try{
bfw.close(); <== exception occured here
pw.close(); <== this is not execute
}catch(Exception e){
e.printStackTrace();
}
}
What if an exception occurs in bfw.close()? pw.close() will never execute. And this leads to a resource leak.
How can I ensure the FileStream is closed?
Someone already pointed out using try/catch/finally inside finally.
But if you don't like to see so many try catch finally I would suggest you to use a library like Apache Commons IO.
Solution:
try {
........
} finally {
IOUtils.closeQuietly(bfw);
IOUtils.closeQuietly(pw);
}
And yes, you always have try-with-resources if using Java 7 or above.
If exception happens when closing bw you will not close pw. Try this:
finally{
try{
bw.close();
} catch(Exception e){
e.printStackTrace();
} finally {
pw.close();
}
}

How to delete file within catch block

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();}
}

Output text to a file with a class method java

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

FileWriter writing into file

How do I use FileWriter to actually write into a file and then open it on notepad and see what I wrote? This is what I tried so far:
package Experimental;
import java.io.*;
public class IO {
public static void main (String args[]) {
File f = new File("testFile.txt");
//Outputting into a file
try {
PrintWriter filePrint = new PrintWriter(
new BufferedWriter(new FileWriter(f,true))
);
filePrint.println("testing, testing, printing into a file (apparently)");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Don't forget to close your FileWriter once you are done writing to it.
You should flush and close the PrintWriter like this:
File file = new File("testFile.txt");
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
try
{
try
{
filePrint.println("testing, testing, printing into a file (apparently)");
filePrint.flush();
}
finally
{
filePrint.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}

Deleting file contents android

I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.
This is what I've tried...
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(path));
bw.write("");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
And I've also tried this...
File f = new File(file);
FileWriter fw;
try {
fw = new FileWriter(f,false);
fw.write("");
}
catch (IOException e) {
e.printStackTrace();
}
Can someone please help me with a solution to this problem.
FileWriter (path, false)
The false will tell the writer to truncate the file instead of appending to it.
Try calling flush() before calling close().
FileWriter writer = null;
try {
writer = ... // initialize a writer
writer.write("");
writer.flush(); // flush the stream
} catch (IOException e) {
// do something with exception
} finally {
if (writer != null) {
writer.close();
}
}
It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.
This works for me:
File f=new File(file);
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

Categories