Shubham Jain
Shubham Jain

Reputation: 17553

Remove the last newline from file in Java

I want to delete the last newline present in my file using java. I mean, there is a newline at the very end of the file, which I want to remove.

I have tried many solutions provided online, but nothing works.

The below code removes all newlines from file

trimm.replace("\n", "").replace("\r", "");

Sample text:

ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821
ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821

The above sample has newline at the end. I have referred the URLs below:

http://www.avajava.com/tutorials/lessons/how-do-i-remove-a-newline-from-the-end-of-a-string.html

https://www.java-forums.org/new-java/22655-removing-last-blank-line-txt-file.html

I can't use split() after \n as many raws have same word

My code:

    String actual ="ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n" + 
            "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n";
    try {
          File fout = new File("I:\\demo\\S2.txt");
          FileOutputStream fos = new FileOutputStream(fout);
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
          String trimm= actual;
/*            StringBuilder sb = new StringBuilder(trimm);
              int lastEnterPosition = trimm.lastIndexOf("\r\n");
              sb.replace(lastEnterPosition, lastEnterPosition + 1, "");
              trimm = sb.toString();*/
              trimm = trimm.replaceAll("[\n\r]+$", "");
              bw.write(trimm);
              bw.newLine();
              bw.close();
            } catch (FileNotFoundException e){
              // File was not found
              e.printStackTrace();
            } catch (IOException e) {
              // Problem when writing to the file
              e.printStackTrace();
            }

Any workaround will be helpful.

Upvotes: 3

Views: 4895

Answers (2)

geco17
geco17

Reputation: 5294

If you know that the string will always end with \r\n, given

String test = "your string that ends with a newline\r\n";

You can use something like

String eol = "\r\n";
int eolLen = eol.length();
String tmp = test.substring(0, test.length()-eolLen);

Using a regex seems a bit overkill. You could optionally check to see that the string really ends with a newline and throw an exception of some kind or another if it's possible that you get bad input. Something like:

String check = test.substring(test.length() - eolLen);
if (!eol.equals(check)) {
    throw new Exception(String.format("Expected newline, found %s", check));
}

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

You can use replaceFirst which use regex with this one [\n\r]+$, like so :

trimm = trimm.replaceFirst("[\n\r]+$", "");

Full code

I tried this piece of code :

public static void main(String[] args) throws Exception {
    String trimm = "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\n" +
            "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n";

    System.out.println("---------------------------------------------------Before replace Start of the input---------------------------------------------------");
    System.out.println(trimm);
    System.out.println("---------------------------------------------------Before replace End of the input---------------------------------------------------");

    System.out.println("---------------------------------------------------After replace Start of the input---------------------------------------------------");
    trimm = trimm.replaceFirst("[\n\r]+$", "");
    System.out.println(trimm);
    System.out.println("---------------------------------------------------After replace End of the input---------------------------------------------------");

}

The output :

---------------------------------------------------Before replace Start of the input---------------------------------------------------
ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821
ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821

---------------------------------------------------Before replace End of the input---------------------------------------------------
---------------------------------------------------After replace Start of the input---------------------------------------------------
ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821
ABC 123|1|2 ABC '123|1|2|"Jan 30 2018  2:34:13:000AM"|dd1|1|"Jan 30 2018  2:56:08:000AM"|EST' ABC 20180821
---------------------------------------------------After replace End of the input---------------------------------------------------

Note that there are a break line before the replace and after the replace only the last break line is removed.

Ideone demo


More details

I tried this three solutions :

Code 1 (Your code)

public static void main(String[] args) throws Exception {
    String trimm = "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\n" +
            "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n";

    try {
        File fout = new File("path");
        FileOutputStream fos = new FileOutputStream(fout);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        trimm = trimm.replaceAll("[\n\r]+$", "");
        bw.write(trimm);
        //bw.newLine();//<-----------------------note this
        bw.close();
    } catch (FileNotFoundException e) {
        // File was not found
        e.printStackTrace();
    } catch (IOException e) {
        // Problem when writing to the file
        e.printStackTrace();
    }
}

Code 2

public static void main(String[] args) throws Exception {
    String trimm = "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\n" +
            "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n";

    Path path = Paths.get("path");

    try (BufferedWriter writer = Files.newBufferedWriter(path))
    {
        writer.write(trimm.replaceFirst("[\n\r]+$", ""));
    }
}

Code 3

public static void main(String[] args) {
    String trimm = "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\n" +
            "ABC 123|1|2 ABC '123|1|2|\"Jan 30 2018  2:34:13:000AM\"|dd1|1|\"Jan 30 2018  2:56:08:000AM\"|EST' ABC 20180821\r\n";

    try {
        Files.write(Paths.get("path"), trimm.replaceFirst("[\n\r]+$", "").getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and all the three codes gives me :

result

Upvotes: 3

Related Questions