'java 파일 목록 저장'에 해당되는 글 1건

 

folderPath와 outputPath는 본인의 경로에 맞춰서 수정해서 이용하면 된다.

 

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileListSaver {
    public static void main(String[] args) {
        // 1. 탐색할 디렉토리 경로 지정
        String folderPath = "C:\\Users\\YourUsername\\Documents";  // 원하는 경로로 수정
        String outputPath = "C:\\Users\\YourUsername\\file_list.txt";  // 저장할 txt 파일 경로

        File folder = new File(folderPath);
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
                for (File file : listOfFiles) {
                    // 1. 파일의 전체 경로를 저장하고 싶을 때
                    writer.write(file.getAbsolutePath());
                    writer.newLine();  // 줄바꿈
                    
					// 2. 만약 파일 이름만 저장하고 싶다면 
                    // String relativePath = file.getAbsolutePath().replace(folderPath + File.separator, "");
					// writer.write(relativePath);
                    // writer.newLine();
                    
                    // 3. 만약 일부 경로만 저장하고 싶다면
                    // String relativePath = file.getAbsolutePath().replace("C:\\Users\\", "");
                    // writer.write(relativePath);
                    // writer.newLine();
                    
                }
                System.out.println("파일 목록이 저장되었습니다: " + outputPath);
            } catch (IOException e) {
                System.err.println("파일 저장 중 오류 발생: " + e.getMessage());
            }
        } else {
            System.err.println("디렉토리를 찾을 수 없거나 파일 목록을 불러올 수 없습니다.");
        }
    }
}
블로그 이미지

Ahan

책, 영화, 게임! 인생의 활력 요소가 되는 취미들을 하자!

,