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?
Related
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();
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
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());
}
}
}
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);
}
I need to write a recursive algorithm to display the contents of a directory in a computer's file system but I am very new to Java. Does anyone have any code or a good tutorial on how to access a directory in a file system with Java??
You can use the JFileChooser class, check this example.
Optionally you can also execute native commands like DIR , lsusing java , here is an example
This took me way too long to write and test, but here's something that should work.
Note: You can pass in either a string or file.
Note 2: This is a naive implementation. Not only is it single-threaded, but it does not check to see if files are links, and could get stuck in an endless loop due to this.
Note 3: The lines immediately after comments can be replaced with your own implementation.
import java.io.*;
public class DirectoryRecurser {
public static void parseFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
if (file.exists()) {
parseFile(file);
} else {
throw new FileNotFoundException(file.getPath());
}
}
public static void parseFile(File file) throws FileNotFoundException {
if (file.isDirectory()) {
for(File child : file.listFiles()) {
parseFile(child);
}
} else if (file.exists()) {
// Process file here
System.out.println(file.getPath());
} else {
throw new FileNotFoundException(file.getPath());
}
}
}
Which could then be called something like this (using a Windows path, because this Workstation is using Windows):
public static void main(String[] args) {
try {
DirectoryRecurser.parseFile("D:\\raisin");
} catch (FileNotFoundException e) {
// Error handling here
System.out.println("File not found: " + e.getMessage());
}
}
In my case, this prints out:
File not found: D:\raisin
because said directory is just one I made up. Otherwise, it prints out the path to each file.
Check out Apache Commons VFS: http://commons.apache.org/vfs/
Sample:
// Locate the Jar file
FileSystemManager fsManager = VFS.getManager();
FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
// List the children of the Jar file
FileObject[] children = jarFile.getChildren();
System.out.println( "Children of " + jarFile.getName().getURI() );
for ( int i = 0; i < children.length; i++ )
{
System.out.println( children[ i ].getName().getBaseName() );
}
If you need to access files on a network drive, check out JCIFS: http://jcifs.samba.org/
check this out buddy
http://java2s.com/Code/Java/File-Input-Output/Traversingallfilesanddirectoriesunderdir.htm
public class Main {
public static void main(String[] argv) throws Exception {
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
For each file you need to check if it is a directory. If it is, you need to recurse. Here is some untested code, which should help:
public void listFiles(File f){
System.out.println(f.getAbsolutePath());
if(f.isDirectory()){
for (File i : f.listFiles()){
listFiles(i);
}
}
}