Java better way to delete file if exists - java

We need to call file.exists() before file.delete() before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.

Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block

file.delete();
if the file doesn't exist, it will return false.

There's also the Java 7 solution, using the new(ish) Path abstraction:
Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
Hope this helps.

Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
A directory to be deleted does not have to be empty.
No exceptions are thrown when a file or directory cannot be deleted.
This offers a one-liner delete call that won't complain if the file fails to be deleted:
FileUtils.deleteQuietly(new File("test.txt"));

I was working on this type of function, maybe this will interests some of you ...
public boolean deleteFile(File file) throws IOException {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f: files) {
deleteFile(f);
}
}
return Files.deleteIfExists(file.toPath());
}
return false;
}

if you have the file inside a dirrectory called uploads in your project. bellow code can be used.
Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
OR
If it is inside a different directory this solution can be used.
File existingFile = new File("D:\\<path>\\img.png");
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}

Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling codes if you want to use.

Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.

Generally We create the File object and check if File Exist then delete.
File f1 = new File("answer.txt");
if(f1.exists()) {
f1.delete();
}
OR
File f2 = new File("answer.txt");
f2.deleteOnExit();
If you are uses the Apache Common then below are the option using which you can delete file and directory
File f3 = new File("answer.txt");
FileUtils.deleteDirectory(f3);
This method throws the exception in case of any failure.
OR
File f4 = new File("answer.txt");
FileUtils.deleteQuietly(f4);
This method will not throw any exception.

This is my solution:
File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) {
f.delete();
}

File xx = new File("filename.txt");
if (xx.exists()) {
System.gc();//Added this part
Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
xx.delete();
}

Related

Get folder from Resources folder JAVA

Hi everyone I can't figure out with this problem : this line of code should work
File[] file = (new File(getClass().getResource("resources/images_resultats"))).listFiles();
I want a list of File, these Files are under "images_resultats" under "resources".
It won't work if resources/images_resultats is not in your classpath and/or if it is in a jar file.
Your code is not even correct it should something like:
File[] file = (new File(getClass().getResource("/my/path").toURI())).listFiles();
You can determine what files are in a folder in resources (even if its in a jar) using the FileSystem class.
public static void doSomethingWithResourcesFolder(String inResourcesPath) throws URISyntaxException {
URI uri = ResourcesFolderUts.class.getResource(inResourcesPath).toURI();
try( FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap() ) ){
Path folderRootPath = fileSystem.getPath(inResourcesPath);
Stream<Path> walk = Files.walk(folderRootPath, 1);
walk.forEach(childFileOrFolder -> {
//do something with the childFileOrFolder
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
inResourcesPath should be something like "/images_resultats"
Note that the childFileOrFolder paths can only be used while the FileSystem remains open, if you try to (for example) return the paths then use them later you've get a file system closed exception.
Change ResourcesFolderUts for one of your own classes
Assuming that resources folder is in classpath, this might work.
String folder = getClass().getResource("images_resultats").getFile();
File[] test = new File(folder).listFiles();

What am i doing wrong with copying my file?

So I am trying to copy one file from one place to the other using the solution found here :
Copying files from one directory to another in Java
My code creates the new directory but cant seem to find the file ,even though the landedtitlesFile is pointing to the proper path and file. I always get my "blast" comment in case you were wondering if my program gets to the end of the method.
Thank you for your time and patience.
private File landedtitlesFile = new File("C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Crusader Kings II\\common\\landed_titles\\landed_titles.txt");
private String modPath = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking";
public void createCopyLandedTitles(Boolean vanilla){
if (vanilla == true) {
File dir = new File(modPath + "\\common\\landed_titles");
dir.mkdir();
try{
FileUtils.copyFile(landedtitlesFile,dir);
}
catch (IOException e ){
System.out.println("blast");
}
}
copyFile expects the second parameter to be the destination file, not a destination directory. You need to give it the target name of the file within that directory:
FileUtils.copyFile(
landedtitlesFile,
new File(dir, landedtitlesFile.getName());
Exception objects generally contain some information on the cause. If you print out the exception with e.printStackTrace(); (or rethrow it up the stack with throw new RuntimeException(e);) then you will be able to see what it says.

Why file.delete() do not remove the resource from disk?

My problem is, I need to delete all the files i.e. first, second, third. But as per below code only third file is getting deleted from path, not first and second. How to remove all files?
ArrayList<File> filesToAdd = new ArrayList<File>();
filesToAdd.add(first);
filesToAdd.add(second);
filesToAdd.add(third);
for (File file : filesToAdd) {
if(file!=null && file.isFile()){
file.delete();
}
}
when I run the app with debugger, if returns true for all files.
And I can't pass file.delete(path) because path is String.
The code you have try to delete files. There are few reasons why File.delete()
you don't have correct permissions to delete
the file the file represents a directory and the directory is not empty
the file is locked by another process, (or even by the same process in say an unclosed FileOutputStream)
the file doesn't exist
The method delete() return a boolean value that inform you about the state.
for (File file : filesToAdd) {
if(file!=null && file.isFile()){
if(file.delete() == false) {
//Add code what should happen
}
}
}
Note that your code is obsolete and use API from Java 6.
If it is possible switch to latest version 8, then you can
List<Path> paths = new ArrayList<>();
paths.add(first);
paths.add(second);
paths.add(third);
for (Path path : paths) {
if(Files.isRegularFile(path)) {
Files.delete(path);
}
}
The change is that Files.delete(path) will throw an exception that will tell you why you can not delete it.

Java's createNewFile() - will it also create directories?

I've got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn't found I want to create it. However, will
File tmp = new File("logs/error.log");
tmp.createNewFile();
also create logs/ if it doesn't exist?
No.
Use tmp.getParentFile().mkdirs() before you create the file.
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();
If the directories already exist, nothing will happen, so you don't need any checks.
Java 8 Style
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
To write on file
Files.write(path, "Log log".getBytes());
To read
System.out.println(Files.readAllLines(path));
Full example
public class CreateFolderAndWrite {
public static void main(String[] args) {
try {
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Files.write(path, "Log log".getBytes());
System.out.println(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
StringUtils.touch(/path/filename.ext) will now (>=1.3) also create the directory and file if they don't exist.
No, and if logs does not exist you'll receive java.io.IOException: No such file or directory
Fun fact for android devs: calls the likes of Files.createDirectories() and Paths.get() would work when supporting min api 26.

How to create a file -- including folders -- for a given path?

Am downloading a zip file from web. It contain folders and files. Uncompressing them using ZipInputstream and ZipEntry. Zipentry.getName gives the name of file as htm/css/aaa.htm.
So I am creating new File(zipentry.getName);
But problem it is throwing an exception: File not found. I got that it is creating subfolders htm and css.
My question is: how to create a file including its sub directories, by passing above path?
Use this:
File targetFile = new File("foo/bar/phleem.css");
File parent = targetFile.getParentFile();
if (parent != null && !parent.exists() && !parent.mkdirs()) {
throw new IllegalStateException("Couldn't create dir: " + parent);
}
While you can just do file.getParentFile().mkdirs() without checking the result, it's considered a best practice to check for the return value of the operation. Hence the check for an existing directory first and then the check for successful creation (if it didn't exist yet).
Also, if the path doesn't include any parent directory, parent would be null. Check it for robustness.
Reference:
File.getParentFile()
File.exists()
File.mkdir()
File.mkdirs()
You can use Google's guava library to do it in a couple of lines with Files class:
Files.createParentDirs(file);
Files.touch(file);
https://code.google.com/p/guava-libraries/
Java NIO API Files.createDirectories
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("/folder1/folder2/folder3");
Files.createDirectories(path);
You need to create subdirectories if necessary, as you loop through the entries in the zip file.
ZipFile zipFile = new ZipFile(myZipFile);
Enumeration e = zipFile.entries();
while(e.hasMoreElements()){
ZipEntry entry = (ZipEntry)e.nextElement();
File destinationFilePath = new File(entry.getName());
destinationFilePath.getParentFile().mkdirs();
if(!entry.isDirectory()){
//code to uncompress the file
}
}
This is how I do it
static void ensureFoldersExist(File folder) {
if (!folder.exists()) {
if (!folder.mkdirs()) {
ensureFoldersExist(folder.getParentFile());
}
}
}
Looks at the file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
isDirectoryCreated = (new File("../path_for_Directory/Directory_Name")).mkdirs();
if (!isDirectoryCreated)
{
// Directory creation failed
}

Categories

Resources