0

I'm working on a code that takes in a couple of inputs and re-write them into a .txt file of my creation but to my dismay the output file can not contain a line-breaker even with the appropriate formatting. I'm using Formatter(java.util)

public void file(Scanner s, Formatter f){
    String s1 = s.nextLine();
    if (!"end".equals(s1)){
        f.format("%s\n%s", s1, "  ");
        file(s,f);
    }
    f.close();
}

public void file(Scanner input,Formatter f,int state){
    String s1 = input.nextLine();
    int loopStop = 0;
    if (state == 1){
        file(input, f);
    } else {
        while (!"end".equals(s1) && loopStop<11){
            f.format("%s\n\n%s", s1, "  ");
            s1 = input.nextLine();
            loopStop++;
        }
        f.close();
    }
}
kbluue
  • 369
  • 1
  • 5
  • 20

3 Answers3

4

Use '%n' for the platform-specific line separator :

f.format("%s%n%n%s", s1, "  ");
fgb
  • 18,439
  • 2
  • 38
  • 52
2

Try with System.getProperty("line.separator")

Read it here about System Properties with complete list of System properties.

The System class maintains a Properties object that describes the configuration of the current working environment.

"line.separator" - Sequence used by operating system to separate lines in text files


Try with System.lineSeparator() as well that states:

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.

On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

Assuming that you're using Windows, you need to use \r\n which is the proper combination of line-break in Windows or simply use System.getProperty("line.separator"); to get the newline combination.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58