2015-09-17 43 views
4

我有我与System.out.format()方法格式化字符串,我做这样的事情:写一个格式化字符串到一个文件 - Java的

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

但是当我尝试写这个格式化字符串到一个文件中,我只能得到像"[email protected]"这样的东西。

寻找到的文档后了解,这种方法有点像System.out.print(),就回到一个PrintStream显示(在控制台为例),所以我试图用.toStringString.valueOf()转换,但我得到了相同的结果。

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

这里是约我使用(只是把有用的零件出现)

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

覆盖'在变量的类对象#toString'。 – Mena

回答

2

String.format是你在找什么,它返回一个String,而不是像PrintStreamSystem.out.format

你的代码应该是:

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

看看Java.lang.String.format() Method进一步的信息。

3

System.out.format回报PrintStreamObjecttoString方法调用是给你[email protected]您正在尝试编写代码。

您应该改用String.format

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

使用

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