Prakash H
Prakash H

Reputation: 852

display path of all files in the folder relative to the first file encountered in that folder

I am new to Java, I tried to practice some example but I am facing issue in the file handling topic.

Following is the example that what I am trying.

 T1--> T2--> T3--> T4--> Gan--> q.txt
                   |
                    -->  Lin-->Img-->s.png
                   |
                    --> p.txt

This is the folder structure. And I want output in the following format.

p.txt
Lin/Img/s.png
Gen/q.txt

That means when the first file is getting in any directory, after that next file will be printed with the path from first file is got.

The above directory structure is not fixed. It may change.

Now following are code that I have did but I am not getting proper output:

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

class FileProgram {

    private ArrayList<File> listOfDirectories = new ArrayList<File>();
    private ArrayList<File> rawFiles = new ArrayList<File>();
    private ArrayList<String> parentDir = new ArrayList<String>();
    private ArrayList<String> filesToDisplay = new ArrayList<String>();
    private Iterator i, listDir;
    private boolean firstFile = false;
    private String parents = "";

    public void getDetails(File file) {
        try {
            if (file.exists()) {
                File directoies[] = file.listFiles();
                if (!rawFiles.isEmpty()) {
                    rawFiles.clear();
                }
                for (File f : directoies) {
                    rawFiles.add(f);
                }

                i = rawFiles.iterator();
                while (i.hasNext()) {
                    File isFile = (File) i.next();
                    if (isFile.isFile()) {
                        displayFiles(isFile);
                    }
                    if (isFile.isDirectory()) {
                        listOfDirectories.add(isFile);
                    }
                }
                iterateInnerDirectories();
            } else {
                System.out.println("Invalid File Path");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        FileProgram ray = new FileProgram();
        ray.getDetails(new File("D:\\Temp"));
    }

    private void iterateInnerDirectories() {
        listDir = listOfDirectories.iterator();
        while (listDir.hasNext()) {
            File isFile = (File) listDir.next();
            File f = isFile;
            listOfDirectories.remove(isFile);
            getDetails(isFile);

        }
    }

    private void displayFiles(File file) {
        if (firstFile == false) {
            firstFile = true;
            String rootPath = file.getParent();
            rootPath = rootPath.replace(file.getName(), "");
            parentDir.add(rootPath);
            parents = file.getParentFile().getName();
            System.out.println(file.getName());
            filesToDisplay.add(file.getName());
        } else {
            String rootPath = file.getParent();
            rootPath = rootPath.replace(file.getName(), "");
            if (parentDir.contains(rootPath)) {
                parents = file.getParentFile().getName();
                System.out.println(file.getName());
                filesToDisplay.add(file.getName());
            } else {
                System.out.println(file);

            }
        }
    }
}

Please anybody can help me to get proper output that I have mentioned above.

Thanks in advance.

Upvotes: 1

Views: 277

Answers (1)

icza
icza

Reputation: 417722

Unless you're using a Java prior to Java 7 I would strongly suggest to use Path.

You can walk a directory recursively using Files.walkFileTree().

Once you encounter a file (!Files.isDirectory()), you can get its parent with Path.getParent(). And you can print the relative path to this parent of all further file using Path.relativize().

Short, Simple Implementation

In this implementation I don't even use Files.isDirectory() because visitFile() is only called for files:

public static void printFiles(Path start) {
    try {
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            Path parent;
            @Override
            public FileVisitResult visitFile(Path file,
                            BasicFileAttributes attrs) throws IOException {
                if (parent == null)
                    parent = file.getParent();
                System.out.println(parent.relativize(file));
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And this is how you call it:

printFiles(Paths.get("/path/to/T1"));

Upvotes: 1

Related Questions