File is not Deleting - java

Am trying to deleting particular file in a folder starting with name TRTHIndicative_.
But files are not deleting,am using below code
testMethod(inputDir);
testMethod(outputFile);
private static void testMethod(String dirName){
File directory = new File(dirName);
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().startsWith("Indicative_")) {
// Delete each file
if(file.exists()){
System.out.println("File is there!");
}
if (file.delete()) {
// Failed to delete file
System.out.println("Failed to delete " + file);
} else {
System.out.println("Deleted file succsfully");
}
}
}
please check and let me know if anything wrong.

You have your if and else confused - File#delete() returns true if the file is successfully deleted. So, the condition should be reversed:
if (file.delete()) {
System.out.println("Deleted file succesfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}

Mureinik is right.
I just tried your peace of code. It works fine. Just do the changes as follows:
public class Main {
public static void main(String[] args) {
File directory = new File("C:/temp");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().startsWith("blub")) {
// Delete each file
if (file.exists()) {
System.out.println("File is there!");
}
if (file.delete()) {
System.out.println("Deleted file succsfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
}
}
}
}
Note the toLowerCase() I added. It will make your snippet easier to use.

I think you have permission error in the file you try to delete.
elToro`s answer is working fine with me as well.
Try to give read/write permission to every user
how to change file permissions in windows

Related

Unable to print directory

My code won't compile. I think it has to do with directory path, because I keep getting error message. I am trying to print out my sample directory( SampleDir) located in Desktop. Can someone help me with the directory path? Thank you in advance!
public class WalkDirectory {
public static void main(String[] args) {
File [] files = new File("C:/SampleDir").listFiles();
showFiles(files);
}
private static void showFiles(File[] files) {
for(File file: files) {
if(file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // files from the existing directory or current directory
}
else {
System.out.println("File: " + file.getName());
}
}
}
Your } characters are misplaced.
The code wad edited and in the edited code, it misses a } character at the end. For info, in the original, one was misplaced and another was missing (the last) I believe.
Try that :
import java.io.File;
public class WalkDirectory {
public static void main(String[] args) {
File[] files = new File("C:/SampleDir").listFiles();
showFiles(files);
}
private static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // files from the existing directory or current directory
}
else {
System.out.println("File: " + file.getName());
}
}
}
}
EDIT
Exception in thread "main" java.lang.NullPointerException at
WalkDirectory.showFiles(WalkDirectory.java:16) at
WalkDirectory.main(WalkDirectory.java:11)
I suppose that the NPE is triggered in the foreach
for (File file : files)
because files array is nulL.
You should write that to check that the folder exists :
public static void main(String[] args) {
final File dirWithFiles = new File("C:/SampleDir");
//check folder exist and is a directory
if (!dirWithFiles.exist()) {
System.out.println("dir " + dirWithFiles + " does not exit");
return;
}
if (!dirWithFiles.isDirectory()) {
System.out.println("dir " + dirWithFiles + " is not a directory");
return;
}
// end check
File[] files = dirWithFiles.listFiles();
showFiles(files);
}
If the folder control fails, you should check in your filesystem that the input folder used in the application exists.
If you are in Windows env, I think the problem is in how you declare the path: "C:/SampleDir"..
Try with something like that:
String path = "C:\\Documents and Settings\\Your User\\Desktop\\SampleDir";
File[] files = new File(path).listFiles();

can not delete files of "Recent" folder using java

I am trying to program a small utility program using java that will delete temp files, recent places etc. When i try to list files of C:\Users\Username\Recent to delete them but it is returning null.
This is what I have tried so far:
public class Simpledeleter {
public static void main(String[] args) {
File folder=new File("C:\\Users\\hp\\Recent");
deleteFolder(folder,false);
}
public static void deleteFolder(File folder,boolean flag) {
File[] files = folder.listFiles();
if(files!=null) {
for(File f: files) {
System.out.println("accessed folder!");
if(f.isDirectory()) {
System.out.println("deleting contents of "+f);
deleteFolder(f,true);
} else {
System.out.println("deleting file "+f);
f.delete();
}
}
}
if(files==null){
System.out.println("returned null!");
}
if(flag==true){
folder.delete();
}
}
}
Am i having permission problems here? Any help on this?

Java file deletion fails

I need to delete files from within a java program and have written this code. It fails to delete the file and I can't figure why. The File is not in use and not write protected.
public static void delfile(String filetodel) {
try {
File file = new File("filetodel");
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed." + filetodel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I guess the issue is this:
File file = new File("filetodel");
This should possibly be (inferred from the parameter filetodel passed in the method):
File file = new File(filetodel);
Everything else seems fine, and is working on my machine.
If you just want to delete the file, there is no need for loading it.
java.nio.file.Files.deleteIfExists(filetodel); (where filetodel contains the path to the file)
Returns true if the file was deleted, so you can even put it in your if-clause.
hey buddy you should use a path as parameter in delete
static void delete(Path path)
Deletes a file.
static boolean deleteIfExists(Path path)
Deletes a file if it exists.
search here: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
so in your case
File file = new File("c://user//filetodel");
file.delete();
or use getAbsolutePath(filename) and use it in file path
Here is my code to delete file.
public class deletef
{
public static void main(String[] args)
{
try{
File file = new File("/home/rahul/Downloads/ou.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
your code is also right but you have to put extension also in your file
File file = new File("filetodel");
here add extension also of file other wise your code will not delete file

get rid of java.lang.NullPointerException in my following program

This program works fine while I search for something inside my /home/meow directory and lists all the files, but when I try to list all the files on my system's "/" it crashes after it prints the contents of the /bin directory. I also tried to execute it as SUDO java pin
import java.io.*;
public class Pin
{
public static void printFiles(String a)
{
File dir = new File(a);
for(File file:dir.listFiles())
{
if(file.isFile())
{
System.out.println(file);
}
else
{
printFiles(file.toString());
}
}
}
public static void main(String[] args)
{
printFiles("/");
}
}
This was my output ...
vikkyhacks java # sudo java Pin
/lib64/ld-linux-x86-64.so.2
/bin/ntfsmove
/bin/init-checkconf
/bin/chown
/bin/mt-gnu
/bin/ntfs-3g.usermap
/bin/mountpoint
/bin/plymouth
/bin/s
/bin/bunzip2
/bin/gzexe
/bin/fgconsole
/bin/ntfstruncate
/bin/i
/bin/plymouth-upstart-bridge
/bin/fgrep
/bin/ping
/bin/lesspipe
/bin/rbash
/bin/gzip
/bin/ntfsmftalloc
/bin/lowntfs-3g
/bin/tailf
/bin/bzcat
/bin/tempfile
/bin/domainname
/bin/touch
/bin/zcmp
/bin/mktemp
/bin/nano
/bin/unicode_start
/bin/ln
Exception in thread "main" java.lang.NullPointerException
at Pin.printFiles(Pin.java:9)
at Pin.printFiles(Pin.java:17)
at Pin.printFiles(Pin.java:17)
at Pin.main(Pin.java:23)
You need to check that a valid array of files are returned from File#listFiles. This can happen in the case of so-called logical files where the file is actually a view of physical files:
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
...
Alternatively you can just process anything this that is a directory
public static void printFiles(String a) {
File[] files = new File(a).listFiles();
if (files != null) {
for (File file: files) {
if (file.isFile()) {
System.out.println(file);
} else if (file.isDirectory()) {
printFiles(file.toString());
}
}
}
}
Your need to check whether the file or directory is exists, by using
File file = new File(a);
if (file.exists()){
for(File file:dir.listFiles())
{
if(file.isFile())
{
System.out.println(file);
}
else
{
printFiles(file.toString());
}
}
}

How to find sub-directories in a directory/folder?

I'm looking for a way to get all the names of directories in a given directory, but not files.
For example, let's say I have a folder called Parent, and inside that I have 3 folders: Child1 Child2 and Child3.
I want to get the names of the folders, but don't care about the contents, or the names of subfolders inside Child1, Child2, etc.
Is there a simple way to do this?
If you are on java 7, you might wanna try using the support provided in
package java.nio.file
If your directory has many entries, it will be able to start listing them without reading them all into memory first. read more in the javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)
Here is also that example adapted to your needs:
public static void main(String[] args) {
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path file) throws IOException {
return (Files.isDirectory(file));
}
};
Path dir = FileSystems.getDefault().getPath("c:/");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
for (Path path : stream) {
// Iterate over the paths in the directory and print filenames
System.out.println(path.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can use String[] directories = file.list() to list all file names,
then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.
For example:
File file = new File("C:\\Windows");
String[] names = file.list();
for(String name : names)
{
if (new File("C:\\Windows\\" + name).isDirectory())
{
System.out.println(name);
}
}
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory Name==>:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println("file Not Acess===>" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
====inside class/Method provide File=URL ======
File currentDir = new File("/home/akshya/NetBeansProjects/");
displayDirectoryContents(currentDir);
}

Categories