Simple file delete code is not working in Java [duplicate] - java

This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}

My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();

Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.

First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:

Related

Android app creates file but can't find it

I'm having an issue that is preventing me from releasing my app, so maybe you can help. I have this code to create and write to a file:
#Override
public void onClick (View view){
final String memoryString = memory.getText().toString();
File file = new File(getApplicationContext().getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
if (location != null) {
String s = location.toString() + " " + memoryString;
Log.d(null, s);
if(fos != null) {
Log.d(null, "fos not null");
fos.write(s.getBytes());
} else {
Log.d(null, "Output Stream is null");
}
fos.close();
Log.d(null, "file created!");
}
} catch (IOException e) {
e.printStackTrace();
}
my log is saying that it's creating the file. but when I go to access and read from said file, I get the error here that it doesn't exist:
try {
File memoryFile = new File(filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
} else {
Log.d(null, "no file found");
}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
Please help if you are able, I am very much stuck
Maybe this ?
try {
File memoryFile = new File(getApplicationContext().getFilesDir(), filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
}else{Log.d(null, "no file found");}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
How is it that you created a file with this statement
File file = new File(getApplicationContext().getFilesDir(), filename);
And then try to retrieve the file with this
File memoryFile = new File(filename);
Why can't you use the same statement. How is the second statement supposed to determine the directory containing the file?

Text document is becoming file folder

Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to save a file to a specific spot on the phone

I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);
Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}

Resources not getting released in java

So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.

Copied android db file is empty

I'm trying to copy an android db file from my application folder to another one on SD card. And from DDMS file explorer i can notice that the copied file size is 0. This is my code bellow.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
return false;
}
}
public void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Is it a permission issue? Thanks for help.
#piyush
Thanks for the try/catch notice. I found the error after adding a log trace in boolean copyDBFile() method at catch block.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("Sarelo", "Error creating file", e);
return false;
}
}
My DB_PATH was already set to /data/data/package/databases/data.db and added to Environment.getDataDirectory() the dbFile result to /data/data/data/package/databases/data.db
That's the big mistake! Thanks all for help :)
try using outChannel.force(true); before using the transferTo(...);

Categories