-3

I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!

Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ScanFolder {

public static void main(String[] args) throws IOException {
    Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            System.out.println(filePath);
        }
    });

}

}
  • Your general idea seems to consist of two parts: How to get a list of all the contents in a folder, and writing data to a file. Do some research on each topic, solve each problem individually, then combine what you have learned to make fully-featured program. – Mage Xy Jan 07 '16 at 20:09
  • I don't know how to write to a text file. I can get the rest of it on my own. I just need a code snippet for writing to a file. – Adam Cochrane Jan 07 '16 at 20:13
  • try this http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java – Ravindra Devadiga Jan 07 '16 at 20:19

1 Answers1

-1

EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter

public static void main(String[] args) {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream("txt.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));

    writeContentsOfFileToAFile(new File("."), out, true); // change true to
                                                            // false if you
                                                            // don't want to
                                                            // recursively
                                                            // list the
                                                            // files

    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
    for (File file : parent.listFiles()) {
        try {
            out.write(file.toString() + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (enterIntoDirectory && file.isDirectory())
            writeContentsOfFileToAFile(file, out, enterIntoDirectory);
    }
}

Is this what you need?

SlumpA
  • 882
  • 12
  • 24