我正在使用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();
}
答案 0 :(得分:0)
你可以这样做
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
}
}
}
答案 1 :(得分:0)
File inputFile = new File("File.txt");
File tempFile = new File("File1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "Thumbnil.jpg";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);