################################## Example 2 ##################################
package com.example.demo.utils.scan;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileScanner {
public static void main(String[] args) throws IOException {
Files.write(
Paths.get("C:\\Users\\j\\Documents\\out.csv"),
getList(new File("C:\\").listFiles(), new StringBuffer()).toString().getBytes(),
StandardOpenOption.TRUNCATE_EXISTING);
}
public static StringBuffer getList(File[] listOfFiles, StringBuffer sb) {
if (listOfFiles != null)
for (File i : listOfFiles)
if (i.isFile()) {
sb.append("\"" + i.getPath() + "\"" + "," + "\""
+ i.length() + "\"" + "," + "\"" + i.lastModified() + "\"" + "\n");
System.out.println(i.getName());
} else if (i.isDirectory()) getList(new File(i.getPath()).listFiles(), sb);
return sb;
}
}
################################## Example 1 ##################################
package org.example;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws IOException {
String out = "C:\\Users\\j\\Documents\\out.txt";
clearfile("", out);
getList("C:\\");
//writefile("in", "C:\\Users\\j\\Documents\\out.txt");
}
public static void getList(String path) throws IOException {
// System.out.println("Hello jeetu!");
String out = "C:\\Users\\j\\Documents\\out.txt";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
long fileSizeInBytes = listOfFiles[i].length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
//long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
//long fileSizeInMB = fileSizeInKB / 1024;
// System.out.println(listOfFiles[i].getName());
writefile(listOfFiles[i].getPath(), out);
writefile("," + fileSizeInBytes, out);
writefile("\n", out);
System.out.println(listOfFiles[i].getName() + "," + fileSizeInBytes);
} else if (listOfFiles[i].isDirectory()) {
//System.out.println("Directory " + listOfFiles[i].getName());
//System.out.println("Directory " + listOfFiles[i].getPath());
getList(listOfFiles[i].getPath());
}
}
}
}
public static void writefile(String content, String path) throws IOException {
Files.write(
Paths.get(path),
content.getBytes(),
StandardOpenOption.APPEND);
}
public static void clearfile(String content, String path) throws IOException {
Files.write(
Paths.get(path),
content.getBytes(),
StandardOpenOption.TRUNCATE_EXISTING);
}
}
References :