【问题标题】:How do I remove specific contents from a text file?如何从文本文件中删除特定内容?
【发布时间】: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 很容易完成。

标签: java file directory


【解决方案1】:

你可以这样做

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
    }

  }
}

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

      【解决方案3】:

      我只是想感谢大家的帮助,但经过大量试验和错误后,我能够找到解决问题的方法。这就是我解决问题的方法,我创建了两种方法

      1. 一种创建包含所有文件夹内容的文件的方法。
      2. 一种获取此文件并使用 选定的内容。

      然后我就用 main 方法调用了这些。然后您将继续删除您的第一个文件。


          // this is the input file from the folder
          public static final File outFile = new File("input.txt");
      
          public static void main(String[] args) throws IOException {     
              getFileContents();
              changeFileContents();
          }
      
          // this method takes all the folder contents and puts
          // it into a text file
          public static void getFileContents() throws IOException{
      
              System.out.print(outFile.getAbsolutePath());
              PrintWriter out = new PrintWriter(outFile);
      
                  Files.walk(Paths.get("C:/Location")).forEach(file -> {
                      if (Files.isRegularFile(file))
                              out.println(file);
                  }); 
              out.close();
          }
      
          // this method takes the previously made text file and makes
          // a new one only adding the file names with Thumbnail.jpg
          public static void changeFileContents() throws IOException {
      
              PrintWriter in = new PrintWriter(new FileWriter("output.txt"));
      
              Scanner scanner = new Scanner(outFile);
                  while (scanner.hasNextLine()) {
                      String line = scanner.nextLine();
                      // checks to see if the image is the one I need
                      if(line.contains("Thumbnail.jpg"))
                          in.println(line);
                  }
              scanner.close();
              in.close();
           }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 2015-03-30
        • 2020-03-05
        相关资源
        最近更新 更多