This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to find all of the files that are named, in the directory that I have chosen. The code that I have works when I do something like C:\Program Files, or C:\Users. But when I do c:/ I get stuck in the recycle bin and get a java.lang.NullPointerException
and stops at c:\$Recycle.Bin\S-1-5-21-1478355014-127360780-1969717230-1002144.
public void DirectorySerch(String target, String dirName){
File f = new File(dirName); System.out.println("H");
if(!f.isDirectory()){
throw new IllegalArgumentException("that is not a valid directory");
}
for(File folderItem : f.listFiles()){
if(folderItem.isDirectory()){
System.out.println(folderItem.getAbsolutePath());
if(!folderItem.equals("")){
DirectorySerch(target,folderItem.getPath());
}
// Return the result if it is not empty
/* if (!result.equals(folderItem.getName())){
files[filesFounfd] = folderItem.getAbsolutePath();
filesFounfd++;
}*/
}else{
if(folderItem.getName().equals(target)){
files[filesFounfd] = folderItem.getAbsolutePath();
System.out.println(folderItem.getAbsolutePath());
filesFounfd++;
}
}
}
}
What can I do to not get this issue as it works in cases when it does not have to deal with the recycle bin?
for(File folderItem : f.listFiles()){
The problem is here. listFiles() can return null, and all this syntax can do with that is throw an NPE. Change to:
File[] files = f.listFiles();
if (files != null) {
for(File folderItem : files){
so it turns out you can fix this by making a try catch around the for loop
public void DirectorySerch(String target, String dirName) {
File f = new File(dirName);
System.out.println("H");
if (!f.isDirectory()) {
throw new IllegalArgumentException("that is not a valid directory");
}
try {
for (File folderItem : f.listFiles()) {
if (folderItem.isDirectory()) {
System.out.println(folderItem.getAbsolutePath());
if (!folderItem.equals("")) {
DirectorySerch(target, folderItem.getPath());
}
} else {
if (folderItem.getName().equals(target)) {
files[filesFounfd] = folderItem.getAbsolutePath();
System.out.println(folderItem.getAbsolutePath());
filesFounfd++;
}
}
}
}catch(NullPointerException sd){
}
}
Related
This question already has answers here:
Delete directories recursively in Java
(26 answers)
Closed 9 years ago.
Here is a code I tried:
import java.io.*;
public class file03 {
public static void main(String[] args) {
File f1 = new File("C:/tempo1/tempo");
f1.mkdirs();
File f2 = new File("C:/test");
if(!f2.exists()) {
f2.mkdir();
}
f1 = new File("C:/tempo1/kempo");
f1.mkdirs();
f1 = new File("C:/tempo1");
String[] t = {};
if(f1.exists()) {
t = f1.list();
System.out.println(t.length + " files found");
}
for(int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
try {
Thread.sleep(3000);
}
catch(Exception e) {}
f2.delete();
f2 = new File("C:/tempo1/test.txt");
try {
f2.createNewFile();
}
catch(Exception e) {}
try {
Thread.sleep(7000);
}
catch(Exception e) {}
File f3 = new File("C:/tempo1/renametesting.txt");
f2.renameTo(f3);
try {
Thread.sleep(5000);
}
catch(Exception e) {}
f3 = new File("C:/tempo1");
f3.delete();
}
}
what I noticed was that while the folder test gets deleted, the folder tempo1 doesn't get deleted. Is it because it contains other folders and files? If so, how can I delete it?
I am using BlueJ IDE.
A folder can not be deleted until all files of that folder are deleted.
First delete all files from that folder then delete that folder
This is code for deleting a folder..
You need to pass the path of the folder only
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : "+ file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
// System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
public class DeleteFolder {
/**
* Delete a folder and all content folder & files.
* #param folder
*/
public void rmdir(final File folder) {
if (folder.isDirectory()) { //Check if folder file is a real folder
File[] list = folder.listFiles(); //Storing all file name within array
if (list != null) { //Checking list value is null or not to check folder containts atlest one file
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) { //if folder found within folder remove that folder using recursive method
rmdir(tmpF);
}
tmpF.delete(); //else delete file
}
}
if (!folder.delete()) { //if not able to delete folder print message
System.out.println("can't delete folder : " + folder);
}
}
}
}
To delete folder having files , no need of loops or recursive search. You can directly use:
FileUtils.deleteDirectory(<File object of directory>);
This function will delete the folder and all files in it
You can use the commons io library FileUtils class :
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)
"Deletes a directory recursively."
I tried to wrote a function who returns all of the txt files from some directory, that in the main I wrote:
File file = new File(dir);
listFiles(file.listFiles());
and the function is:
private static void listFiles(File[] files) {
if (null == files)
return;
for (File file : files) {
if (!file.isDirectory()) {
if (file.getName().endsWith("txt") && file != null) {
queue.add(file);
fileCounter++;
}
} else {
listFiles(file.listFiles());
}
}
}
and every time it throw "java.lang.NullPointerException" in the "`queue.add(file);"
what is the problem?
You must instantiate your queue (queue = new ...) before you can actually add anything to it.
This means queue is null - probably you didn't initialize it.
This question already has answers here:
How to open a file with the default associated program
(4 answers)
Closed 9 years ago.
I have a files list. Lets say it looks:
String[] lst = new String[] {
"C:\\Folder\\file.txt",
"C:\\Another folder\\another file.pdf"
};
I need some method to open these files with default program for them, lets say "file.txt" with Notepad, "another file.pdf" with AdobeReader and so on.
Does anyone knows how?
There is a method to do this:
java.awt.Desktop.getDesktop().open(file);
JavaDoc:
Launches the associated application to open the file.
If the specified file is a directory, the file manager of the current platform is launched to open it.
The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.
If you are using J2SE 1.4 o Java SE 5, the best option is:
for(int i = 0; i < lst.length; i++) {
String path = lst[i];
if (path.indexOf(' ') > 0) {
// Path with spaces
Runtime.getRuntime().exec("explorer \"" + lst[i] + "\"");
} else {
// Path without spaces
Runtime.getRuntime().exec("explorer " + lst[i]);
}
}
Just make sure the file is in the right location, and this should work fine.
try
{
File dir = new File(System.getenv("APPDATA"), "data");
if (!dir.exists()) dir.mkdirs();
File file = new File(dir"file.txt");
if (!file.exists()) System.out.println("File doesn't exist");
else Desktop.getDesktop().open(file);
} catch (Exception e)
{
e.printStackTrace();
}
I didn't know you have a String array now. So, this one uses regex to process the file list in the format you specified before. Ignore if not required.
If the file list is huge and you would prefer that the files open one by one cmd works great. If you want them to open all at once use explorer. Works only on Windows but then on almost all JVM versions. So, there's a trade-off to consider here.
public class FilesOpenWith {
static String listOfFiles = "{\"C:\\Setup.log\", \"C:\\Users\\XYZ\\Documents\\Downloads\\A B C.pdf\"}";
public static void main(String[] args) {
if (args != null && args.length == 1) {
if (args[0].matches("{\"[^\"]+\"(,\\s?\"[^\"]+\")*}")) {
listOfFiles = args[0];
} else {
usage();
return;
}
}
openFiles();
}
private static void openFiles() {
Matcher m = Pattern.compile("\"([^\"]+)\"").matcher(listOfFiles);
while (m.find()) {
try {
Runtime.getRuntime().exec("cmd /c \"" + m.group(1) + "\"");
// Runtime.getRuntime().exec("explorer \"" + m.group(1) + "\"");
} catch (IOException e) {
System.out.println("Bad Input: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
private static void usage() {
System.out.println("Input filelist format = {\"file1\", \"file2\", ...}");
}
}
I'm developing a shell in Java. This shell can execute the command find 'regex'. This command finds all the files which have a name that matches the regex, recursively. The method that finds the files is:
public void findFile(String regExp, String dirName) {
File dir = new File(dirName);
if (dir.canRead() == false)
return;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile() == true)
if (file.getName().matches(regExp) == true)
System.out.println(file.getAbsolutePath());
if (file.isDirectory() == true && file.canRead() == true) {
findFile(regExp, file.getAbsolutePath());
}
}
}
But this command fails if directory cannot be opened. For example, in D: partition, I have a hidden directory named found.00 (this directory might belong to the system) and I cannot open this directory. When the method encounters this directory, it fails. How can I check if directory belongs to the system and cannot be opened?
As you use file.canRead() already I would say you could surround the complete content of method findFile(String regExp, String dirName) with a try-catch. You can then catch and log or also ignore the access error. Try the following one please.
public void findFile(final String regExp, final String dirName) {
try {
final File dir = new File(dirName);
if (dir.canRead() == false) {
return;
}
final File[] files = dir.listFiles();
for (final File file : files) {
if (file.isFile() && file.getName().matches(regExp)) {
System.out.println(file.getAbsolutePath());
}
if ((file.isDirectory()) && (file.canRead())) {
findFile(regExp, file.getAbsolutePath());
}
}
} catch (final IOException ignore) {
System.out.println("No access to '"+dirName+"'.");
}
}
I have this section of code:
public static void delete(File f) throws IOException
{
if (f.isDirectory())
{
for (File c : f.listFiles())
{
delete(c);
}
}
else if (!f.delete())
{
throw new FileNotFoundException("Failed to delete file: " + f);
}
}
public static void traverseDelete(File directory) throws FileNotFoundException, InterruptedException
{
//Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
if (file.getName().equalsIgnoreCase("word"))
{
boolean containsMedia = false;
File[] filesInWordFolder = file.listFiles();
for ( File file2 : filesInWordFolder )
{
if ( file2.getName().contains("media"))
{
containsMedia = true;
break;
}
}
if (containsMedia == false)
{
try
{
delete(file.getParentFile());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else if (file.isDirectory())
{
traverseDelete(file);
}
}
}
Sorry for the lack of commenting, but it's pretty self-explanatory, I think. Essentially what the code is supposed to do is traverses a set of files in a given directory, if it encounters a directory named "word", then it should list out the contents of word, and then if a directory called "media" does NOT exist, recursively delete everything within the parent directory of "word" down.
My main concern comes from this conditional:
if(!filesInWordFolder.toString().contains("media"))
Is that the correct way to say if the files in that array does not contain an instance of "image", go ahead and delete?
That won't work.
File[] filesInWordFolder = file.listFiles();
if(!filesInWordFolder.toString().contains("media"))
will give you a string representation of a File array -- which will typically have a reference.
You have to iterate through the files to find out if there's any in there that contain the word media.
boolean containsMedia = false;
for ( File file : filesInWordFolder ) {
if ( file.getName().contains("media") ){
containsMedia = true;
break;
}
// now check your boolean
if ( !containsMedia ) {
Well using toString() will give you a String representation of the file (in this case the files). The String representation should contain the file name. If your set purpose is to check for any instance of a file containing the word "media" in the directory, you are fine.
In the example you are printing the String representation of the File array. Instead you should iterate through the File array and check the String representation of each individual File as so:
for (int i = 0; i < file_array.length; i++) {
if ((File)file_array[i]).toString().equals("your_search_term")) {
// The file contains your search term
} else {
// Doesn't contain the search term.
}
}