Writing a formatted string to a file - Java

I have a line that I format with a method System.out.format(), I do something like:

System.out.format("I = %3d  var = %9.6f", i, myVar);

but when I try to write this formatted string to a file, I only get something like "java.io.PrintStream@84fc8d".

After studying the documentation, it was clear that this method is a bit like System.out.print()and just returns PrintStream for display (for example, in the console), so I tried to convert it with .toStringor String.valueOf(), but I get the same result.

So, I was wondering if there is a way to format the string, as the method does String.out.format(), but in a way that will be writable in a file?

Here is roughly the code I'm using (just creating useful parts)

WRITE_MY_LINE(System.out.format(" I = %3d  var = %9.6f", i, myVar).toString());
//also tried this :
WRITE_MY_LINE(String.valueOf(System.out.format(" I = %3d  var = %9.6f", i, myVar)));

public static void WRITE_MY_LINE(String line) {
        buff_out = new BufferedWriter(new FileWriter(ascii_path, true));

        buff_out.append(line);
        buff_out.newLine();
        buff_out.flush();
}
+4
4

String.format - , , String, PrintStream System.out.format.

:

WRITE_MY_LINE(String.format(" I = %3d  var = %9.6f", i, myVar));

Java.lang.String.format().

+2

System.out.format PrintStream Object toString java.io.PrintStream@84fc8d, .

String.format.

WRITE_MY_LINE(String.format(" I = %3d  var = %9.6f", i, myVar));
+3

WRITE_MY_LINE(String.format(" I = %3d  var = %9.6f", i, myVar));
+2

java.util.Formatter java 7. :

java.util.Formatter

+1

Source: https://habr.com/ru/post/1607788/


All Articles