How to delete file within catch block - java

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

Related

Is there any usage for nested try if without catch?

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.

PrintWriter object variable cannot resolve to type when used in try with resources

I'm trying to create a new PrintWriter object within a try with resources block as below, but it's giving me an error saying outFile cannot be resolved to a type:
public class DataSummary {
PrintWriter outFile;
public DataSummary(String filePath) {
// Create new file to print report
try (outFile = new PrintWriter(filePath)) {
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
EDIT:
A reason why I didn't want to declare the PrintWriter object within the try block is because I want to be able to reference the outFile object in other methods of my class.
It seems like I can't do it with try with resources, so I created it within a normal try/catch/finally block.
The text file is being created. However, when I try to write to file in another method, nothing seems to be printing in the text file, test.txt.
Why is this??
public class TestWrite {
PrintWriter outFile;
public TestWrite(String filePath) {
// Create new file to print report
try {
outFile = new PrintWriter(filePath);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} finally {
outFile.close();
}
}
public void generateReport() {
outFile.print("Hello world");
outFile.close();
}
}
Instead of trying to do everything in a constructor, I will demonstrate the preferred way to use a try-with-resources and invoke another method. Namely, pass the closeable resource to the other method. But I strongly recommend you make the opener of such resources responsible for closing them. Like,
public void writeToFile(String filePath) {
try (PrintWriter outFile = new PrintWriter(filePath)) {
generateReport(outFile);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
private void generateReport(PrintWriter outFile) {
outFile.print("Hello world");
}

Not 100% sure on Try /Catch

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 )

Can't delete the file after writing some data to it, where is wrong?

I'm write some text a file then delete it, but the deletion is failed.
The code is very simple:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestFile {
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
public static void writeFile(File file, String content) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
}
}
The output is:
Deleted? false
And there is a file abc.txt contains hello still there under c:.
Then I use FileUtils.writeStringToFile(...) from commons-io.jar instead, the file will be deleted.
But I don't know where is wrong with my code, please help me to find it out.
You are only closing the file if you get an IOException.
Change it to a finally block and you will be able to close and delete the file.
public static void writeFile(File file, String content) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(content.getBytes("UTF-8"));
} finally {
try {
out.close();
} catch (IOException ignored) {
}
}
}
You need to close your OutputStream when you finished writing the file.
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
out.close();
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
In your main method,
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
You open the file, write to it and then do not close it. Java keeps the file open for you, so if you wanted to add more information to it, you could. However, to be able to delete the file, you need to make sure no other reference is open to it. You can do this by using file.close() to close the file handle Java reserves for you.
It's best practice to always close a stream when you are done with it, especially if you added data to it. Otherwise, you might run into situations where you are keepings files open by accident, or, in extreme cases, lose data you thought was saved already.
Have a look at what FileUtils.writeStringToFile() does that you haven't.
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = new java.io.FileOutputStream(file);
try {
out.write(data.getBytes(encoding));
} finally {
IOUtils.closeQuietly(out);
}
}
You will note that the out stream is always closed, wheras in your example it only gets closed in your catch block if the write() throws an exception.
On Windows, files that are open by any program cannot be deleted.
You just delete your file if an exception occurs. You need to do that every time, after you opened the file.
You may want to put close into a finally block.
If you're using Java 7 I consider using a try-with-ressources block, which takes care of closing files for you.
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}

Do I have to close FileOutputStream which is wrapped by PrintStream?

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.

Categories