0

My task is to insert the directory path to the command line and write the results of Files.walkFileTree () operation to the file in "Tree" format. I have the following code:

public class IOTask {
public static void main(String[] args) {
        File file = new File(args[0]);
        if (file.exists() && file.isDirectory()) {
            Path files = Paths.get(args[0]);
            PrintFiles pf = new PrintFiles();
            try {
                Files.walkFileTree(files, pf);
            } catch (IOException e) {
                e.printStackTrace();
            }

Args [0] is the path "e://Music//Accept//". To write the results to the file I use FileVisitor.

public class PrintFiles extends SimpleFileVisitor<Path> {
private FileOutputStream outputStream;
private final Path baseFolder = Paths.get("e://Music//Accept//");

public PrintFiles() {
    try {
        this.outputStream = new FileOutputStream("data/File.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
    Path relative = baseFolder.relativize(dir);
    int count = relative.getNameCount();
    try {
        this.outputStream.write("|-----\t".repeat(count) + dir.getFileName() + System.getProperty("line.separator"));
    } catch (IOException | NumberFormatException e) {
        e.printStackTrace();
    }
    return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
    Path relative = baseFolder.relativize(file);
    int count = relative.getNameCount();
    if  (attr.isRegularFile()) {
        try {
            this.outputStream.write("|\t".repeat(count) + file.getFileName() + System.getProperty("line.separator"));
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return FileVisitResult.CONTINUE;
}

}

Counting the folders with .relativize(dir) I expect to obtain the following "Tree" result in the file:

|----Accept

 |----First album

      |file...
      |file...

 |----Second album

      |file...

and so on... But something goes wrong... I need help. Thank you in advance!

Shubt
  • 17
  • 6
  • What goes wrong? – Slaw May 28 '21 at 08:10
  • @Slaw I have a compile error in 2 `FileVisitor's`strings that start with `this.outputStream.write`. And the compiler suggests the only option to wrap using `Intager.parseInt()`. When I do so the program throws NumberFormatException because I need `String` not `Int`. I don't know what to do :( I'm a beginner – Shubt May 28 '21 at 08:40
  • The `InputStream` / `OutputStream` (and their subclasses) deal with streams of _bytes_. You want to write _characters_. So you should use a `Writer`. For instance, you can use `BufferedWriter writer = Files.newBufferedWriter(Path.of("data", "File.txt"));`. Note that uses UTF-8 encoding by default, though you can specify a different encoding if you want. The encoding is what translates a character into one or more bytes and vice versa. – Slaw May 28 '21 at 08:44
  • @Slaw I have changed `OutputStream` to `BufferedWriter`. Yes, it compiles without errors and the program works... But I still have `File.txt` empty :( – Shubt May 28 '21 at 09:24
  • Do you get an exception? If so, please post the stack trace. – Slaw May 28 '21 at 09:25
  • @Slaw No, there is no exception after program finishes. But the "File.txt" remains empty. – Shubt May 28 '21 at 09:34
  • Add print statements at strategic places within your code. Make sure the code you expect to be running is actually running. Also print out important values to make sure the input and output is what you expect. Does the walked directory actually have descendants? And make sure you're checking the correct `File.txt`. It should be located at `data/File.txt` relative to the _working directory_. – Slaw May 28 '21 at 09:48
  • @Slaw I followed your advice. The program prints all the information I need. And I've changed directory path. And I've found out that if directory is big (contains a lot of sub dirs and files) `BufferedWriter` writes some part of its content to the file and stops writing at some moment. As if it ran out of time. And if directory is small `BufferedWriter` doesn't write at all. May be I need to construct the `while` loop so that `BufferedWriter` has time to work out? – Shubt May 28 '21 at 10:30
  • Try calling `writer.flush()` after writing. Or `close()` the writer after you've walked the entire tree. – Slaw May 28 '21 at 10:39

0 Answers0