Remove all empty lines

后端 未结 7 1625
误落风尘
误落风尘 2020-11-27 17:22

I thought that wasn\'t that hard to do, but I want to remove all empty lines (or lines just containing blanks and tabs in Java) with String.replaceAll.

My regex look

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 18:03

    I have some code without using regexp, just import org.apache.commons.lang3.StringUtils;

      File temporaire = new File("temp.txt");
      try {
        Scanner scanner = new Scanner(yourfile);
        BufferedWriter bw = new BufferedWriter(new FileWriter(temporaire));
        while (scanner.hasNextLine()) {
          String line = StringUtils.stripEnd(scanner.nextLine(),null); // Clean blanks at the end of the line
          if (StringUtils.isNotBlank(line)) {
            bw.write(line); // Keep the line only if not blank
            if (scanner.hasNextLine()){
              // Go to next line (Win,Mac,Unix) if there is one
              bw.write(System.getProperty("line.separator"));
            }
          }
          bw.flush();
        }
        scanner.close();
        bw.close();
        fichier.delete();
        temporaire.renameTo(fichier);
      }
      catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
      }
      catch (IOException e) {
        System.out.println(e.getMessage());
      }
    }
    

提交回复
热议问题