0

I have a problem with some java code. I'm returning a text from a method, which is on a .txt file. Then, I'm storing this text to a variable "text" and writing this on another .txt file. But the problem is: this new .txt file gets a new blank line at the bottom. That's because inside my method read, the variable "text" is receiving a "\n". How can I solve this problem? PS: I'm doing this with educational purposes.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;

public class Arquivo {
    public static void main(String[] args) {
        String text = read("in.txt");
        write(text, "out.txt");
        System.out.println("Text created!");
    }

    public static String read(String arquivo) {
        String text = "";
        try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {

            String line = br.readLine();
            while (line != null) {
                text += line + "\n";
                line = br.readLine();
            }

        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
        return text;
    }

    public static void write(String text, String arquivo) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(arquivo))) {
            bw.write(text);
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
}

My two created files "in.txt" and "out.txt".

this is a text file.

this is a text file. (blank line)

vini290
  • 13
  • 3
  • Is it the trailing, final, **one** `"\n"` character you're removing, or more than one? Because if it's just the one, read this: [**Why should text files end with a newline?**](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline) You **want** a text file to end with a newline/blank line, so if someone does `cat file1.txt file2.txt ...` the last line of `file1.txt` doesn't get merged with the first line of `file2.txt`. – Andrew Henle May 17 '19 at 20:31

6 Answers6

0

please try this:

String line = br.readLine();
while (line != null) {
    text += line;
    line = br.readLine();
    if (line!=null){
        text +=  "\n";
    }
}

you can try this variant:

String line;
while((line = br.readLine()) != null) {
    text += line;
    if (line!=null){
        text +=  "\n";
    }
}
0

A good solution to this type of problem is to add the newline before you write each additional line:

String line = br.readLine();
text += line;
while ((line = br.readLine()) != null) {
    text = "\n" + line;
}

This way, you only add the newline for each additional line you write (no extraneous ones at the end). Notice the assignment (plus null check) in the while loop).

java-addict301
  • 3,220
  • 2
  • 25
  • 37
0

replace write(text, "out.txt"); with

write(text.substring(0,text.length()-1), "out.txt");

which will remove the last character, which is the /n before writing.

Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23
0

Just do not add \n before the last line:

    String text = "";
    ...
        String line = br.readLine();
        boolean addNewLine = false; 
        while (line != null) {
            if (addNewLine) {
                text += "\n";
            } else {
                addNewLine = true;
            }
            text += line;
            line = br.readLine();
        }

Also, for performance improvement, consider using a StringBuilder instead of the string concatenation:

    StringBuilder sb = new StringBuilder();
    ...
        String line = br.readLine();
        boolean addNewLine = false; 
        while (line != null) {
            if (addNewLine) {
                sb.append('\n');
            } else {
                addNewLine = true;
            }
            sb.append(line);
            line = br.readLine();
        }
    ...
    String text = sb.toString();
AterLux
  • 4,566
  • 2
  • 10
  • 13
  • `text.length() != 0` doesn't identify the last line, it identifies **all** empty lines. – Andrew Henle May 17 '19 at 20:34
  • Andrew Henle, you're right, but it works if lines are not empty. I have changed the source so it can handle empty lines too. – AterLux May 17 '19 at 21:58
0

Store all the strings in a list, then join on the line feed

public static void main( String[] args ) {
    String text = read( "in.txt" );
    write( text, "out.txt" );
    System.out.println( "Text created!" );
}

public static String read( String arquivo ) {
    List<String> texts = new ArrayList<>();
    try ( BufferedReader br = new BufferedReader( new FileReader( arquivo ) ) ) {

        String line = br.readLine();
        while ( line != null ) {
            texts.add( line );
            line = br.readLine();
        }

    } catch ( IOException e ) {
        System.err.println( e.getMessage() );
    }
    return texts.stream().collect( Collectors.joining( "\n" ) );
}

public static void write( String text, String arquivo ) {
    try ( BufferedWriter bw = new BufferedWriter( new FileWriter( arquivo ) ) ) {
        bw.write( text );
    } catch ( IOException e ) {
        System.err.println( e.getMessage() );
    }
}
RobOhRob
  • 585
  • 7
  • 17
0

String.trim()

public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()

Simply trim the string before you return it from read.

public static String read(String arquivo) {
        String text = "";
        try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {

            String line = br.readLine();
            while (line != null) {
                text += line + "\n";
                line = br.readLine();
            }

        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
        return text.trim();
    }
Red
  • 16
  • 3
  • this will have the undesired side effect of trimming leading white space (e.g., suppose the text has an indent at the first paragraph that the person wants to keep). – Jeremy Kahan May 17 '19 at 20:46
  • That's right though given the use case I thought the OP might want a simple solution. All of the other answers here are over kill or do not really answer his question. – Red May 17 '19 at 20:53