Recursively file search not working - java

What i wanna do is to recursively search for some files on the external sd-card. The problem is that the code is looking ok, but (assuming .txt files) it only shows me 7 files out of 100+ that are being spread throughout folders.
The code is this:
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
void makelist(File file){
if(file.isFile()){
if(SimpleAdapter.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
Any idea how could i make it run correctly?

Assuming you are building two lists (misc files and doc files), try with below code which all all files other than text files to misc and text files to doc.
if(SimpleAdapter.getFileType(file) == null || !SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
mis.add(file);
else
doc.add(file);
Not sure why it is not working for you. Tried a test program and it worked perfectly...
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileChecker
{
/**
* #param args
*/
public static void main(String[] args) {
SimpleAdapterTest adapter = new SimpleAdapterTest();
adapter.makelist(new File("C:\\MYFolder"));
adapter.showList();
}
}
class SimpleAdapterTest
{
List<File> mis = new ArrayList<File>();
List<File> doc = new ArrayList<File>();
public static String getFileType(File f)
{
String Name = f.getName();
if (f.getName().endsWith(".txt") || Name.endsWith(".TXT")
|| Name.endsWith(".inf") || Name.endsWith(".INF"))
return "text";
return null;
}
public void makelist(File file){
if(file.isFile()){
if(SimpleAdapterTest.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapterTest.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
public void showList()
{
for(File miscFile : mis)
{
System.out.println("Misc files = " + miscFile.getName());
}
for(File docfile : doc)
{
System.out.println("Doc files = " + docfile.getName());
}
}
}

Related

Console doesn't display result

I'm writing some code to get the latest file from a directory but the console doesn't display any result.
Here's the code I've written :
import java.io.File;
public class test {
public static File getLastModified(String directoryFilePath)
{
File directory = new File("C:\\New folder");
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
System.out.println(file);
}
}
}
return chosenFile;
}
public static void main(String[] args) {}
}
You have to do 2 things,.
Need to call getLastModified() method in your main method
Scanner reading each line in the file and doing system. print calls? while (scanner.hasNextLine()) { System.out.println(blah blah blah); }
Simple. Done!

Recursion method to display the directory structure of a path (Java)

Our teacher gave us question to Write a recursive method to display the directory structure of a path.
He want the output to look like this :
testdir
+--f1
+--d2
+--d22
+f221
+f212
+f211
+--f2
+--d1
+--f12
I used this method :
package Task;
import java.io.File;
import java.io.IOException;
public class Recursive {
public static void main(String[] args) {
File currentDirectory = new File(" . "); // current directory
displayDirectoryContents(currentDirectory);
}
public static void displayDirectoryContents(File dirct) {
File[] myfiles = dirct.listFiles();
for (File file : myfiles) {
if (file.isDirectory()) {
//it worked when i used file.getCanonicalPath()); but file.getName()); does not work
System.out.println("directory : " + file.getName());
displayDirectoryContents(file);
}
else {
//it worked when i used file.getCanonicalPath()); but file.getName()); does not work
System.out.println(" files : " + file.getName());
}
}
}
}
The getName does not work and give me an erorr (
Exception in thread "main" java.lang.NullPointerException
at lab16.displayDirectoryContents(lab16.java:17)
at lab16.main(lab16.java:10)
)
i've rewritten algorithm and it works with .getName() without any problem. I didn't do any indentations tho.
import java.io.File;
public class Recursive {
private static void TraverseDirectory(File[] files) {
if (files.length == 0) return;
for (File file : files) {
if (file.isFile()) System.out.println(file.getName());
else {
// is DIR
System.out.println(file.getName());
TraverseDirectory(file.listFiles());
}
}
}
public static void main(String[] args) {
File cur_dir = new File("/");
TraverseDirectory(cur_dir.listFiles());
}
}
EDIT: after you edited your question, I can now see what was the problem. You weren't returning anything when the content of the directory was empty (it was null). Therefore, it couldn't traverse null value.

How find files in a directory knowing a part of the name

I have a problem, i have this directory with 1k+ files and some folders. I need find the path of the files(which are in subdirectories) that starts with "BCM", but not only the first i find but every single file which start with that.
I tried looking at other answers about this topic but i couldn't find help,
tried using this code:
File dir = new File("K:\\Jgencs");
FilenameFilter filter = new FilenameFilter()
{
public boolean accept (File dir, String name)
{
return name.startsWith("BCM");
}
};
String[] children = dir.list(filter);
if (children == null)
{
System.out.println("No directory found");
}
else
{
for (int i = 0; i< children.length; i++)
{
String filename = children[i];
System.out.println(filename);
File h = new File(dir,filename);
System.out.println(h.getAbsolutePath()
[UPDATED] This is how you can achieve using plain Java and filter text from a variable passing as parameter:
Here is my directory: /tmp
And here is the code running:
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GetAllFilesInDirectory {
public static void main(String[] args) throws IOException {
String filter = "BCM";
List<File> files = listFiles("/tmp", new CustomerFileFilter(filter));
for (File file : files) {
System.out.println("file: " + file.getCanonicalPath());
}
}
private static List<File> listFiles(String directoryName, CustomerFileFilter fileFilter) {
File directory = new File(directoryName);
List<File> files = new ArrayList<>();
// Get all files from a directory.
File[] fList = directory.listFiles(fileFilter);
if(fList != null) {
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
files.addAll(listFiles(file.getAbsolutePath(), fileFilter));
}
}
}
return files;
}
}
class CustomerFileFilter implements FileFilter {
private final String filterStartingWith;
public CustomerFileFilter(String filterStartingWith) {
this.filterStartingWith = filterStartingWith;
}
#Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile() && file.getName().startsWith(filterStartingWith);
}
}
This is the output:
file: /private/tmp/BCM01.txt
file: /private/tmp/BCM01
file: /private/tmp/subfolder1/BCM02.txt
Doing recursive calls to the method when finding a directory to also list the files form inside, and filtering by name the files before adding.
You want Files.walk:
try (Stream<Path> files = Files.walk(Paths.get("K:\\Jgencs"))) {
files.filter(f -> f.getFileName().toString().startsWith("BCM")).forEach(
file -> System.out.println(file));
}

Iterate through all files in Java

I want to make my program print huge list of all files that I have on my computer. My problem is that it only prints files from first folder of the first hard-drive, when I want it to print all files located on my computer. Any ideas what am I doing wrong here? Thanks.
Here is code I use:
Main:
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<File> roots = new ArrayList();
roots.addAll(Arrays.asList(File.listRoots()));
for (File file : roots) {
new Searcher(file.toString().replace('\\', '/')).search();
}
}
}
and Searcher class:
import java.io.File;
public class Searcher {
private String root;
public Searcher(String root) {
this.root = root;
}
public void search() {
System.out.println(root);
File folder = new File(root);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
String path = file.getPath().replace('\\', '/');
System.out.println(path);
if (!path.contains(".")) {
new Searcher(path + "/").search();
}
}
}
}
I just tried this and it worked for me. I did have to add one null check and changed the directory evaluation method though:
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class Searcher {
public static void main(String[] args) {
ArrayList<File> roots = new ArrayList<File>();
roots.addAll(Arrays.asList(File.listRoots()));
for (File file : roots) {
new Searcher(file.toString().replace('\\', '/')).search();
}
}
private String root;
public Searcher(String root) {
this.root = root;
}
public void search() {
System.out.println(root);
File folder = new File(root);
File[] listOfFiles = folder.listFiles();
if(listOfFiles == null) return; // Added condition check
for (File file : listOfFiles) {
String path = file.getPath().replace('\\', '/');
System.out.println(path);
if (file.isDirectory()) {
new Searcher(path + "/").search();
}
}
}
}
You should update your search method like this:
public void search() {
System.out.println(root);
File folder = new File(root);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
String path = file.getPath().replace('\\', '/');
System.out.println(path);
if (file.isDirectory()) {
new Searcher(path + "/").search();
}
}
}
If Java 7 is an option, look into the walkFileTree() method. It will allow you to visit all files and directories in a tree, which you can start from the root of your drive. Just implement a basic FileVisitor to process the file attributes for each Path. You can get started here.
If you're using Java SE 7, use the new file API:
http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitor.html
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.util.Set,%20int,%20java.nio.file.FileVisitor%29
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.nio.file.FileVisitor%29
I don't know what error you are getting but I got a NPE because you are not checking for the null after the following line.
File[] listOfFiles = folder.listFiles();
After changing the code as follows it seemed to run fine , I stopped it because I have a lot of files. I am assuming it will go on to the next root after the first root(c:/ in my case)
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
ArrayList<File> roots = new ArrayList();
roots.addAll(Arrays.asList(File.listRoots()));
for (File file : roots) {
System.out.println(file.toString());
new Searcher(file.toString().replace('\\', '/')).search();
}
}
}
class Searcher {
private String root;
public Searcher(String root) {
this.root = root;
}
public void search() {
System.out.println(root);
File folder = new File(root);
File[] listOfFiles = folder.listFiles();
if(listOfFiles!=null)
{
for (File file : listOfFiles) {
String path = file.getPath().replace('\\', '/');
System.out.println(path);
if (!path.contains(".")) {
new Searcher(path + "/").search();
}
}
}
}
}

how to delete all files having specific extention from MY Computer by java

HI I want to write a java program by which I can delete all the files of my computer having a specific extension or character pattern in name.I also want to apply wild card character on the name of file.
Thanks in advance
For your program to be really useful you need to do some more thinking, but for a starter;
import java.io.File;
import java.util.regex.Pattern;
private static void walkDir(final File dir, final Pattern pattern) {
final File[] files = dir.listFiles();
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
walkDir(file, pattern);
} else if (pattern.matcher(file.getName()).matches()) {
System.out.println("file to delete: " + file.getAbsolutePath());
}
}
}
}
public static void main(String[] args) {
walkDir(new File("/home/user/something"), Pattern.compile(".*\\.mp3"));
}
Sidenote (not an answer, but you didn't ask something): Be aware of recursion.
public void deleteFilesWithExtension(final String directoryName, final String extension) {
final File dir = new File(directoryName);
final String[] allFiles = dir.list();
for (final String file : allFiles) {
if (file.endsWith(extension)) {
new File(aDirectoryName + "/" + file).delete();
}
}
}

Categories