ディレクトリを走査してファイルの絶対パスと相対パスを出力する

指定したディレクトリ内にあるファイルの絶対パス相対パスを取得する。

package practice;

import java.io.File;
import java.io.IOException;

public class GetFilePathList {
	public static void main(String args[]) throws IOException {
		//String prefixPath = "C:\\Users\\YouName";
		String prefixPath = "path/to/directory";
		System.getProperty("file.separator");

		File dir = new File(prefixPath);
		getPathList(dir, prefixPath);

		String basename = dir.getName();
		getRelativePathList(dir, basename);
	}

	private static void getPathList(File dir, String prefixPath) {
		File items[] = dir.listFiles();

		for (File item : items) {
			if (item.isDirectory()) {
				getPathList(item, prefixPath);
			} else if (item.isFile()) {
				try {
					if (item.exists()) {
						System.out.println(item.getCanonicalPath());
					}
				} catch(IOException e) {
					e.printStackTrace();
				}

			}
		}
	}

	private static void getRelativePathList(File dir, String relativeFilePath) {
		if (dir.isDirectory()) {
			String paths[] = dir.list();
			Integer length = paths.length;

			for (int i = 0; i < length; i++) {
				File childFile = new File(dir, paths[i]);
				String nextPath = relativeFilePath + File.separatorChar + childFile.getName();
				getRelativePathList(childFile, nextPath);
			}
		} else {
			System.out.println(relativeFilePath);
		}
	}
}