【发布时间】:2015-08-16 02:26:42
【问题描述】:
我在 Java 中的 SO 的帮助下正在处理这个项目,我正在读取一个文件夹,然后将内容写入文件。然后,我需要浏览该内容,只保留最后带有 Thumbnail.jpg 的图像。
编辑:
public static final File outFile = new File(System.getProperty("user.home") + "/Desktop/output.txt");
public static void main(String[] args) throws IOException {
getFileContents();
}
public static void getFileContents() throws IOException{
System.out.print(outFile.getAbsolutePath());
PrintWriter out = new PrintWriter(outFile);
Files.walk(Paths.get("C:/Location")).forEach(filePath -> {
//this is where I would like to happen
if (Files.isRegularFile(filePath)) // I was thinking I could use filePath.endsWith("Thumbnail.jpg")
out.println(filePath);
});
out.close();
}
【问题讨论】:
-
不能使用
!=比较字符串,必须使用! str.equals("T")。另外,字符串是不可变的,所以string.trim()什么都不做,你需要说string = string.trim()。 -
如果您要查找以“Thumbnail.jpg”结尾的字符串值,请使用
string.endsWith("Thumbnail.jpg")。 -
您似乎也误解了
substring(start)。它返回字符串的其余部分,从给定位置开始。如果您只想要该位置的字符,请使用string.charAt(start)。 -
没错。如果这最终成为您问题的答案,您应该回答自己的问题并接受它作为最终答案,以便其他人可以轻松看到。
-
哦,你不应该忽略“资源”警告。在这种情况下,它告诉您您没有关闭阅读器,这非常重要,并且使用 try-with-resources 很容易完成。