java - 无法将 .txt 文件移动到 java 中的存档文件夹
问题描述
我需要将所有以 .txt 结尾的文件移动到存档文件夹。
我有以下代码,但if (sourcepath.endsWith(".txt"))
不验证文件扩展名。
File directory = new File("Archive");
System.out.println((System.getProperty("user.dir")));
File directory1 = new File (System.getProperty("user.dir"));
File[] files = directory1.listFiles();
if (! directory.exists()) {
directory.mkdir();
for(File f : files ) {
Path sourcePath = Paths.get(f.getName());
System.out.println(sourcePath);
if (sourcePath.endsWith(".txt")){ // Not validating
System.out.println(sourcePath.endsWith(extension));
Files.move(sourcePath, Paths.get("Archive"));
}
}
System.out.println("Clearing Folder.....All Files moved to Archive Directory");
}
预期输出:
C:\Users\harsshah\workspace\FFPreBatchValidation
.classpath
.project
.settings
bin
kjnk.txt
src
kjnk.txt 应该移动到存档文件夹
解决方案
测试此路径是否以 Path 结尾,通过转换给定的路径字符串构造,完全按照 endsWith(Path) 方法指定的方式。例如,在 UNIX 上,路径“foo/bar”以“foo/bar”和“bar”结尾。它不以“r”或“/bar”结尾。请注意,不考虑尾随分隔符,因此使用字符串“bar/”在路径“foo/bar”上调用此方法会返回 true。
重要的部分是:It does not end with "r" or "/bar"
您必须将其转换Path
为 aString
并调用String.endsWith(String)
而不是Path.endsWith(String)
推荐阅读
- python - 用 python 正则表达式替换文本中的列表
- python - 多找美汤
- r - 读入满足 R 中特定要求的表
- javascript - 无法验证在客户端使用 Javascript 创建的服务器端的 RSA 签名
- url - 将 /home/opencart/public_html/opencart 更改为 localhost URL(将服务器 URL 更改为 localhost URL)
- javascript - 在 .vue 组件中合并多个数据
- python - 为什么执行列表推导比在 for 循环中使用 += 需要更长的时间?
- javascript - jinja2.exceptions.TemplateSyntaxError:预期的令牌',',得到'静态'
- java - 与 just_a_name.cer 和 just_a_name.p7b 的 SSL 连接以导入到 Java 中的 cacerts 失败
- docker - 在 DigitalOcean 液滴上托管的基于 Debian 的 Docker 映像上的 apt-get 更新失败