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

我正在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();
}

参考方案

你可以这样

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:从文件系统加载资源 - java

我的项目设定我有以下项目设置:\program.jar \images\logo.png 在我的代码中,我使用相对URL "images/logo.png"引用图像。问题如果我在目录中使用以下命令运行此程序:c:\projects\program_dir\bin\>java -jar program.jar 然后一切正常,Java能…

Java-搜索字符串数组中的字符串 - java

在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…

Java:线程池如何将线程映射到可运行对象 - java

试图绕过Java并发问题,并且很难理解线程池,线程以及它们正在执行的可运行“任务”之间的关系。如果我创建一个有10个线程的线程池,那么我是否必须将相同的任务传递给池中的每个线程,或者池化的线程实际上只是与任务无关的“工人无人机”可用于执行任何任务?无论哪种方式,Executor / ExecutorService如何将正确的任务分配给正确的线程? 参考方案 …

对于Java中的isDirectory和isFile,文件始终返回false - java

为什么file为isFile()方法返回false,即使它是file。当它是目录时,它为isDirectory()返回false。难道我做错了什么?我测试的这些文件/目录不存在,我需要创建它们,所以这就是为什么我要测试使用createFile()还是mkdir()的原因。File file = new File("C:/Users/John/Des…

JAVA:字节码和二进制有什么区别? - java

java字节代码(已编译的语言,也称为目标代码)与机器代码(当前计算机的本机代码)之间有什么区别?我读过一些书,他们将字节码称为二进制指令,但我不知道为什么。 参考方案 字节码是独立于平台的,在Windows中运行的编译器编译的字节码仍将在linux / unix / mac中运行。机器代码是特定于平台的,如果在Windows x86中编译,则它将仅在Win…