폴더 아래의 파일을 열거합니다. 귀속 및 비귀속 실현

2441 단어
package com.robert;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Main3 {
    public static void main(String args[]) {
        File file = new File("/Users/robert/Downloads/ /");
        try {
            StringBuffer stringBuffer = new StringBuffer();
            printFilePath(file, stringBuffer);
            File logFile = new File("/Users/robert/Documents/log.txt");
            logFile.delete();
            FileWriter fileWriter = new FileWriter(logFile, true);
            fileWriter.write(stringBuffer.toString());
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void printFilePath(File file, StringBuffer stringBuffer) throws IOException {
        if (!file.exists()) {
            throw new RuntimeException("file is not exist");
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File tempFile : files) {
                printFilePath(tempFile, stringBuffer);
            }
        } else {
            stringBuffer.append(file.getAbsolutePath()).append("
"); } } public static void printFilePath2(File file) throws IOException { if (!file.exists()) { throw new RuntimeException("file is not exist"); } File logFile = new File("/Users/robert/Documents/log2.txt"); logFile.delete(); FileWriter fileWriter = new FileWriter(logFile, true); List files = new LinkedList<>(); if (file.isDirectory()) { Collections.addAll(files, file.listFiles()); } else { // System.out.println(file.getAbsolutePath()); fileWriter.write(file.getAbsolutePath()); } while (files.size() > 0) { File tempFile = files.get(0); files.remove(tempFile); if (tempFile.isDirectory()) { Collections.addAll(files, tempFile.listFiles()); } else { // System.out.println(tempFile.getAbsolutePath()); fileWriter.write(tempFile.getAbsolutePath()); fileWriter.write("
"); } } fileWriter.close(); } }

좋은 웹페이지 즐겨찾기