java FileUtils.delete() not deleting folder - java

Whats wrong with my code ? with reference with this question
the folder is not being deleted.
File f = new File(directory+"\\OOO");
if (f.exists())
{
System.out.println(f);
FileUtils.delete(f);
f.delete();
// f.mkdir();
}
else
{
System.out.println("created");
//f.mkdir();
}

FileUtils does not contain any method named delete();
You should use deleteDirectory() to recursively delete directory.
Or you can also use deleteQuitely() to suppress any exceptions while deletion.

FileUtils does not contain any method named delete(), so you should use deleteDirectory() instead. Also, please ensure you have imported the correct Java file utility class from Apache Commons IO. If it is not the case, your need to
Download Apache Commons IO as a JAR file, link it to the classpath
Or declare a dependency the Apache Commons IO in your Maven, or other dependency management system.
Here's the code:
import org.apache.commons.io.FileUtils;
public class YourClass
{
public void yourMethod() throws IOException
{
File f = new File(directory+"\\OOO");
if (f.exists())
{
FileUtils.deleteDirectory(f);
}
...
}
}

This may help
try {
FileUtils.deleteDirectory(new File("path");
//path Example - C:\\myfolder\\foldertodelete
} catch (IOException e) {
}

Related

Exclude File Filter

I used the following code to filter files that are having the following extension
FileFilter fileFilter= new WildcardFileFilter("*.docx");
File[] sampleFiles= filesDirectory.listFiles(fileFilter);
But what if I want the opposite, I want to exclude files that are having this extension.
Currently I have the following code
public class FileFilter {
public static void main(String[] args) {
File dir = new File("C:\\temp\\filter-exclude");
File[] files = dir.listFiles(new ExcludeFilter());
for (File f : files) {
System.out.println("file: " + f.getName());
}
}
public static class ExcludeFilter implements java.io.FileFilter {
#Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith("docx")) {
return false;
}
return true;
}
}
}
But not sure if there are classes already for this.
Is there such a class?
You could compose with the notFileFilter:
dir.listFiles(
FileFilterUtils.notFileFilter(
FileFilterUtils.suffixFileFilter(".docx")))
There is not built-in FileFilter implementations that handle common cases such as yours.
To shorter you could use an anonymous class or better a lambda as FileFilter is a functional interface such as :
File[] files = dir.listFiles(f -> !f.getName().toLowerCase().endsWith("docx"));
As you're using commons-io already, have a look at NotFileFilter.
Given your use-case, an example looks like that:
FileFilter fileFilter = new NotFileFilter(new WildcardFileFilter("*.docx"))
File[] files = dir.listFiles(fileFilter);
Is there any specific reason you're not using the nio package and instead use the old io?
By using the nio package you can get your code to shrink considerably. Also you'll be using what is the best tools to operate with file and the filesystem in general. Have a look at the snippet below:
var matcher = FileSystems.getDefault().getPathMatcher("*.docx");
try {
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:\\temp"), entry -> !matcher.matches(entry));
stream.forEach(path -> System.out.println("file: " + path.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
Effectively this does what your code does, using nothing but the out of the box API provided by the nio package to list directories and filter files based on their suffix.

Downloading a csv file in target folder and renaming it

I have been trying to download a file in a target folder and rename it. This should be automatically done. Is this possible?
If yes, how should the code be written in Java?
Not too sure where you are trying to download from but as mentioned this my help: stackoverflow.com/a/921400/6743203
Alternatively refer to: https://www.mkyong.com/java/java-how-to-download-a-file-from-the-internet/
The renaming should look something like this, without a code example though it's hard to say what exactly you need:
import java.io.File;
public class FileRenameExample
{
public static void main(String[] args)
{
File oldFileName =new File("path/to/old_file_name.txt");
File newFileName =new File("path/to/new_file_name.txt");
if(oldFileName.renameTo(newFileName)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}
File f = new File("YOUR-PATH/FileName.EXTENSION");
File fNew = new File("YOUR-PATH/NEW-FileName.EXTENSION");
if(f.renameTo(fNew)){
//do something
}
else{
//handle exception or throw custom exception
}

Java opening File Streams in one class and closing/deletion of file in another class

I want to delete the file which is opened and done writing but not closed. Please refer to code below:
Class A (can't be changed):
import java.io.FileOutputStream;
public class A {
public void run(String file) throws Exception {
FileOutputStream s = new FileOutputStream(file);
}
}
Class B:
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class B {
public static void main(String[] args) throws Exception {
String path = "D:\\CONFLUX_HOME\\TestClient\\Maps\\test\\newTest.txt";
A a = new A();
a.run(path);
File f = new File(path);
Files.delete(Paths.get(f.getAbsolutePath()));
}
}
In Class A , just open the stream without closing the file.
In class B , calling A's run method and then try to delete the file.
Since the file is still opened. I'm unable to delete the file.
Error is :
The process cannot access the file because it is being used by another process.
Actual Scenario is :
We are loading the jars dynamically. Classes inside jar are creating the file. When there is an exception, a file gets created whose size will be 0 bytes. We need to delete this file. Since the file is not closed during the exception, we can't delete the file.
We could fix the issue if we could close the streams in the jar classes, but we can't modify the jars that create the files as they are client specific jars.
Please suggest how to delete the opened file, without modifying the code in class A.
Make sure you close the file, even if there was an Exception when writing to it.
E.g.
public void run(String file) throws Exception {
FileOutputStream s = null;
try {
s = new FileOutputStream(file);
} finally {
try {
s.close();
} catch(Exception e) {
// log this exception
}
}
}
You have to close the file before any delete operation as firstly its a bad practice and second is it will lead to memory leaks.
If you are using Tomcat, it is possible to set AntiLockingOption and antiJARLocking in $CATALINA_HOME/conf/context.xml for Windows:
<Context antiJARLocking="true" antiResourceLocking="true" >
Important note:
The antiResourceLocking option can stop JSPs from redeploying when they are edited requiring a redeploy.
Read more about this option:
http://tomcat.apache.org/tomcat-7.0-doc/config/context.html
antiResourceLocking:
If true, Tomcat will prevent any file locking. This will significantly impact startup time of applications, but allows full webapp hot deploy and undeploy on platforms or configurations where file locking can occur. If not specified, the default value is false.
Pass the resource as a parameter and it becomes the caller's responsibility to clear up the resources
public void run(FileOutputStream stream) throws Exception {
...
}
caller:
try(FileStream stream = new FileStream(path)){
A a = new A();
a.run(stream);
}catch(Exception e){
.. exception handling
}
Updated according to OPs comment.
Another approach could be to subclass A and override run().
public static void main(String[] args) throws Exception {
String path = "D:\\CONFLUX_HOME\\TestClient\\Maps\\test\\newTest.txt";
A a = new A() {
#Override
public void run(String file) throws Exception {
FileOutputStream s = new FileOutputStream(file);
s.close();
}
};
a.run(path);
File f = new File(path);
Files.delete(Paths.get(f.getAbsolutePath()));
System.out.println("foo");
}
I don't think you'll find a pure java solution to this problem. One option is to install Unlocker (being careful to hit "Skip" on all the junkware) and invoke it from your code.
If you have UAC enabled, you'll also need to be running your java in an elevated process (e.g. start command prompt as Administrator). Then, assuming unlocker is in C:\Program Files\Unlocker:
Process p = new ProcessBuilder("c:\\Program Files\\Unlocker\\Unlocker.exe",path,"-s").start();
p.waitFor();
And after that you can delete the file as before. Or you could use "-d" instead of "-s" and Unlocker will delete the file for you.

Extracting Text From JPG

I've tried this code and added the needed jar files but still I'm getting an error message like Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302'.
Is there a complete tutorial how to extract text and what things should be done to address the error? Any help is appreciated...
import net.sourceforge.tess4j.*;
import java.io.File;
public class ExtractTxtFromImg {
public static void main(String[] args) {
File imgFile = new File("C:\\Documents and Settings\\rueca\\Desktop\\sampleImg.jpg");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try {
String result = instance.doOCR(imgFile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
In addition to adding the jars, you also need to add the natives. You can do so with Djava.library.path="C:\[absolute path to dir containing *.dll files and such]"
Note that you need to provide the directory, not the file itself.

Java: opening a resource (txt file) which is in a jar with OS standard application

i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()

Categories

Resources