首页 > 学院 > 开发设计 > 正文

获取指定目录下的文件

2019-11-08 02:58:01
字体:
来源:转载
供稿:网友

1. 将指定目录下的所有文件复制到指定目录。 该方式只能获取指定目录中只有一个文件,且该文件在最底层的形式。

2. 文件复制,使用的是jdk1.7中的api。

3. 如果想获取目录下所有的文件, 可以定义一个map, 遍历目录,判断File是文件时,将其添加到map中, 最后在对其操作。

				public static void main(String[] args) throws IOException {		String rootDir = "E://tmp//video//videos";		String destDir = "E://tmp//video//videosall//";		Path source = null;		Path target = null;		File rootFile = new File(rootDir);		File[] files = rootFile.listFiles();		StringBuilder sb = new StringBuilder();		File retFile = null;		for (File file : files) {			retFile = getVideoFile(file, sb);//执行完成后, retFile为当前目录下的最底层文件, sb为该文件的路径			source = Paths.get(rootDir + sb.toString());			target = Paths.get(destDir + retFile.getName());			Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // 复制文件到指定目录, 文件已存在则覆盖原有文件			sb.setLength(0); // 清空目录记录		}	}		/**	 * 	 * @desc: 获取目标文件中最底层的文件,及其路径, 只能用于目标目录中只有一个文件的情况	 * @auth: zona	 * 2017年2月18日 上午10:35:13 	 * @param filee	 * @param sb	 * @return	 */	public static File getVideoFile(File filee, StringBuilder sb) {				if(filee.isDirectory()) {			sb.append("/"+filee.getName());			File[] rootFiles = filee.listFiles();			for (File file : rootFiles) {				// TODO 这里需要return, 但是还不知道原因				return getVideoFile(file, sb);			}		}else {			sb.append("/"+filee.getName());		}		return filee;	}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表