Java I/O. delete() method not deleting created file from directory - java

This code creates a .txt in the folder directory (it works) but when comes the time to delete the whole directory or the .txt file using delete() method, nothing happens.
The delete() method works only when I replace the .txt file with an ordinary folder
import java.io.*;
public class Filemkdir {
public static void main(String[] args) throws Exception {
File f = new File("C:/Temp/Java/secret.txt");
FileWriter fSecret = new FileWriter(f);
f.mkdir();
f.delete();
}
}

On Windows you can't delete an open file. Close the FileWriter first.
Also, the
f.mkdir();
seems completely pointless.

Maybe the fSecret (FileWriter) needs to be closed first. Otherwise the file is "in use"
fSecret.close();

You would basically need to close the writer object before deleting the file

File delete work on file, if you are trying to delete directory you first need to delete all files inside id.
with your code you are giving path for file, but you are creating directory after that.

Related

Casting multiform part to a file

I have a managed bean. An HTML/JSF page sends a zipped file as a Part. I need to extract the contents from it, but to do that I need it to be File. Is it possible to cast the Part to File like as follows, and then treat it like a normal zip file?
Part xmlFile;
public void myMethod()
{
File zippedFile = (File) getXmlFile();
....
}
If not, how would I go about doing so? I've looked on online but there seems to be very little information.
You can create a temporary file:
File aFile = File.createTempFile(PREFIX, SUFFIX);
And write the contents of your Part payload into that file:
try (InputStream input = part.getInputStream()) {
Files.copy(input, aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
You may also want to make use of File's delete() or deleteOnExit() for cleaning up resources. Bear in mind that deleteOnExit() is only invoked when the JVM exits, which may not be what you want in your case.

java.io.IOException source exists but not in a directory

I am a real beginner at Java programming so I hope I'm not wasting anyone's time. I tried my best to research this but couldn't come up with a solution.
I am following the Lynda video series "Java Essential Training" and it's been very good so far. I am currently learning how to copy the contents of a text file onto a new text file. However, the video shows a alternative method by downloading commons IO from Apache commons and adding the .jar file to the project.
In the video the jar file was added to build path. My version of eclipse seemed to do it automatically as "Referenced Libraries" popped up, and when I tried to add it eclipse said it was already there.
I followed the video exactly. The code looks like this
package com.lynda.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");
FileUtils.copyDirectory(f1, f2);
System.out.println("File copied!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I ran the code I got the message in console
java.io.IOException: Source 'loremipsum.txt' exists but is not a directory
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1371)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1261)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1230)
at com.lynda.files.Main.main(Main.java:16)
In the code it says the FileUtils imported but eclipse tells me "The source attachment does not contain the source for file FileUtils.class". I tried to change the attached source but it gave me the error "Could not write to file BlahBlahBlah.classpath (Access is denied)
Hopefully I didn't drone on about something obvious and simple. I thought it best to be as clear as possible in case someone else has a similar problem.
Edit
I feel so stupid. Thank you for your help. I clicked on "copyDirectory" instead of "copyFile". Next time, instead of panicking, googling every line of error and asking people for help, I'll take the time to go through each line and think about what it does. Thanks to all of you for your help and patience.
See (http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29)
Use FileUtils.copyFile(f1, f2); instead of FileUtils.copyDirectory(f1, f2);
The source and target File parameters of copyDirectory must be directories, but you are suppling text files.
public static void copyDirectory(File srcDir,File destDir)
throws IOException
Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.
Parameters:
srcDir - an existing directory to copy, must not be null
destDir - the new directory, must not be null
Throws:
NullPointerException - if source or destination is null
IOException - if source or destination is invalid
IOException - if an IO error occurs during copying
Since:
1.1
(Source)
I found this that may be of help to you:
copyFile(File srcFile, File destFile) Copies a file to a new location preserving the file date.
static void copyFile(File srcFile, File destFile, boolean preserveFileDate) Copies a file to a new location.
static long copyFile(File input, OutputStream output) Copy bytes from a File to an OutputStream.
static void copyFileToDirectory(File srcFile, File destDir) Copies a file to a directory preserving the file date.
static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.
Source
Although it's from the Apache site, it does talk about the Java classes.
Please read the error message again:
Source 'loremipsum.txt' exists but is not a directory
This is not exactly what you wrote in your subject. Indeed the file 'loremipsum.txt' exists but it not a directory. It is regular file. However you try to call FileUtils.copyDirectory() and pass this regular file to this method. But this method is not ready to work with files. It supports directories only. This is exactly what is written in error message.
EDIT
Now the question is why do you call method that definitely for intended for directories with parameters that are definitely files?

rewrite file instead of recreating a file

I have the following piece of code which allows me to recreate a file holding updated data. Even though I used the "StandardOpenOption.TRUNCATE_EXISTING" option to overwrite the old file I was getting an error saying that the file already exists and it wouldn't write on top of it!
File filename = new File("data.txt");
public void writeToFile(char[] data){
filename.delete();
Files.write(filename.toPath(), data, StandardOpenOption.TRUNCATE_EXISTING);
}
Is it possible instead of deleting and recreating the same file over and over to edit the initial file's data?
Thank you
EDIT1: It seems like it was a mistake of mine. Together with "StandardOpenOption.TRUNCATE_EXISTING" I have included "StandardOpenOption.CREEATE_NEW".
This is because I want the file to be created in case it doesn't already exist! How is it possible to first try to edit it and if it doesnt exist create a new one?
Sorry for my initial mistake
The way to go on this one (which worked for me) is creating a try{}catch{} block and within the "try" try to edit the file and if it fails because it doesn't exist create a new file in the "catch".
Look at the JavaDoc of the write method in the Files class, it says: "By default the method creates a new file or overwrites an existing file", so it seems that all you need to do is:
File filename = new File("data.txt");
public void writeToFile(char[] data) throws IOException {
Files.write(filename.toPath(), data);
}

what is in java importing packages

import java.io.*;
public class createfile{
public static void main(String args[]) throws IOException{
File f=new File("javafile.txt");
if(f.exists())
{
f.createNewFile();
System.out.println("New file \"javafile.txt\"has been created to the current directory");
}
else
System.out.println("The specified file is already exist");
}
}
I created a existing file "javafile.txt". i entered some text into this.. If i compile javac, i hope that file must be recreated by the following codes
if(f.exists())
{
f.createNewFile();
}
but it didn't create.. when i open it, the existing file opens. why?
File.createNewFile() create new file if not exists already.
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with
this name does not yet exist. The check for the existence of the file
and the creation of the file if it does not exist are a single
operation that is atomic with respect to all other filesystem
activities that might affect the file.
From the documentation (emphasis mine):
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
This is exactly how the method is supposed to work.

Force rename a file in Java

Can I use any utility to do a force rename of a file from Java.io?
I understand that Java 7 has these features, but I can’t use it...
If I do a
File tempFile = File.createTempFile();
tempFile.renameTo(newfile)
and if newfile exists then its fails.
How do I do a force rename?
I think you have to do it manually - that means you have to check if the target-name exists already as a file and remove it before doing the real rename.
You can write a routine, to do it:
public void forceRename(File source, File target) throws IOException
{
if (target.exists()) target.delete();
source.renameTo(target)
}
The downside of this approach is, that after deleting and before renaming another process could create a new file with the name.
Another possibility could be therefore to copy the content of the source into the the target-file and deleting the source-file afterwards. But this would eat up more resources (depending on the size of the file) and should be done only, if the possibility of recreation of the deleted file is likely.
You could always delete newFile first:
File newFile = ...
File file = ...
newFile.delete();
file.renameTo(newFile);
I was unable to rename whenever a folder is open. Setting the following property in Java solved my issue:
dirToRename.setExecutable(true);

Categories