gpt4 book ai didi

java - 如何从文本文件中删除特定内容?

转载 作者:行者123 更新时间:2023-12-03 23:07:05 26 4
gpt4 key购买 nike

我在 SO in java 的帮助下从事这个项目,我正在读取一个文件夹,然后将内容写入文件。然后,我需要浏览该内容,只保留最后带有 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();
}

最佳答案

你可以这样做

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// My test file. Change to your path
File file = new File("/home/andrew/Desktop/File.txt");
if (!file.exists()) {
throw new RuntimeException("File not found");
}

try {
Scanner scanner = new Scanner(file);

//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
// If Thumbnail.jpg is anyone where on the line
if(line.contains("Thumbnail.jpg")){
// print the line for example. You can do whatever you what with it now
System.out.println("Found item on line: " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}

}
}

关于java - 如何从文本文件中删除特定内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com