本文介绍了将格式化的字符串写入文件-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用System.out.format()方法格式化的字符串,我做了类似的事情:

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

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

但是当我尝试将此格式化的字符串写入文件时,我只得到类似"java.io.PrintStream@84fc8d"的东西.

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

查看文档后了解到,此方法有点像System.out.print(),只是返回一个PrintStream进行显示(例如在控制台中),所以我尝试使用.toStringString.valueOf()对其进行转换,但是我得到了结果相同.

After looking into the documentation understood that this method is a little like System.out.print() and just return a PrintStream to display (in console for example), so I tried converting it with .toString or String.valueOf() but I get the same result.

所以我想知道是否有一种像String.out.format()方法一样格式化字符串的方法,但是这种方法可以在文件中写入吗?

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

这里大约是我使用的代码(只是显示有用的部分)

Here is approximately the code I use (just making the useful parts appear)

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();
}

推荐答案

String.format 是您要查找的内容,它返回String并且不是像System.out.format这样的PrintStream.

String.format is what you are looking for it returns a String and not a PrintStream like System.out.format.

您的代码应为:

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

看看 Java.lang.String.format()方法 ,以获取更多信息.

Take a look at Java.lang.String.format() Method for further information.

这篇关于将格式化的字符串写入文件-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 09:32