0

How is possible to write a string in a file .txt exactly how it is?

For example, I want to write exactly the following string :

Hello, I'm an user of stackoverflow

and I'm asking a question

I tried with BufferedWriter, PrintWriter, PrintStream, but the result is always the same, so in my file .txt the string appears like this :

Hello, I'm an user of stackoverflow and I'm asking a question

It is necessary to analyze each character or is there an easier way?

Fabrizio
  • 51
  • 1
  • 9

3 Answers3

2

Use any one

Sample code: (Try any one)

try (BufferedWriter writer = new BufferedWriter(new FileWriter("abc.txt"))) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.newLine();
    writer.write("and I'm asking a question");
}

try (PrintWriter writer = new PrintWriter(new FileWriter("abc.txt"))) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.println();
    writer.write("and I'm asking a question");
}

try (FileWriter writer = new FileWriter("abc.txt")) {
    writer.write("Hello, I'm an user of stackoverflow");
    writer.write(System.lineSeparator());
    writer.write("and I'm asking a question");
}

Read more about Java 7 The try-with-resources Statement to handle the resources carefully.

Braj
  • 46,415
  • 5
  • 60
  • 76
2

The problem seems to be the line breaks.

If you use PrintWriter.println() the platform specific line separator is used: "\r\n" on Windows.

Windows Notepad will not handle "\n" but WordPad does.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

You can use the newLine() method of BufferedWriter class.

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

You may try like this using \n as well:

String s ="Hello, I'm an user of stackoverflow\n"
          +"and I'm asking a question";

or

String s = String.format("%s\n%s","Hello, I'm an user of stackoverflow",
              "and I'm asking a question");
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331