我在这个空间遇到了麻烦。 如何正确打印输出文件? 当我运行我的代码时,就像......
这是我的main方法的样子,并生成输出文件......
main()....{
File stats = new File(statFile);
stats.createNewFile();
// my code here.... the stat values change here.
FileWriter statFileWriter = new FileWriter(stats, true);
BufferedWriter statsOutput = new BufferedWriter(statFileWriter);
statsOutput.write(Stats.printStat());
statsOutput.flush();
}
这是我可以更改程序中的值的Stat类,并打印出带有值的字符串。
public class Stats {
public static String dataFile = "";
public static int cacheHits = 0;
public static int diskReads = 0;
public static int diskWrites = 0;
public static long executionTime = 0;
public static String printStat() {
String print = "";
print += "Sort on " + dataFile;
print += "\nCache Hits: " + cacheHits;
print += "\nDisk Reads: " + diskReads;
print += "\nDisk Writes: " + diskWrites;
print += "\nTime is " + executionTime;
return print;
}
}
这应该输出如下:
Sort on sorted_b.dat
Cache Hits: 30922
Disk Reads: 1
Disk Writes: 1
Time is 16
Sort on sorted_a.dat
Cache Hits: 62899
Disk Reads: 2
Disk Writes: 2
Time is 0
但是当我在测试用例中运行main两次时,实际输出是:
Sort on sorted_b.dat
Cache Hits: 30922
Disk Reads: 1
Disk Writes: 1
Time is 16Sort on sorted_a.dat ------> the new stat is not start from the nextline.
Cache Hits: 62899
Disk Reads: 2
Disk Writes: 2
Time is 0
如果我添加额外" / n"在结束时 print + =" \ nTime is" + executionTime;这条线就像 print + =" \ nTime is" + executionTime + \ n;
最后会增加一行,比如
Sort on sorted_b.dat
Cache Hits: 30922
Disk Reads: 1
Disk Writes: 1
Time is 16
Sort on sorted_a.dat
Cache Hits: 62899
Disk Reads: 2
Disk Writes: 2
Time is 0
------------blank, but extra line.
如何在没有额外线的情况下打印输出,并正确打印?
答案 0 :(得分:1)
将您的主要方法更改为:
File stats = new File(statFile);
Boolean fromStart = stats.createNewFile();
// my code here.... the stat values change here.
FileWriter statFileWriter = new FileWriter(stats, true);
BufferedWriter statsOutput = new BufferedWriter(statFileWriter);
if(fromStart == false) statsOutput.write("\n");
statsOutput.write(Stats.printStat());
statsOutput.flush();
从Boolean fromStart
返回的 stats.createNewFile()
将是:
true
如果文件是第一次创建的 - >无需添加额外换行符。false
如果文件已存在 - >在编写新内容之前需要添加换行符。答案 1 :(得分:0)
你需要在结尾追加“\ n”
public class Stats
{
public static String dataFile = "";
public static int cacheHits = 0;
public static int diskReads = 0;
public static int diskWrites = 0;
public static long executionTime = 0;
public static String printStat()
{
String print = "";
print += "Sort on " + dataFile;
print += "\nCache Hits: " + cacheHits;
print += "\nDisk Reads: " + diskReads;
print += "\nDisk Writes: " + diskWrites;
print += "\nTime is " + executionTime+"\n";
return print;
}
}
答案 2 :(得分:0)
在您的主要方法中,只需使用BufferedWriter
的{{3}}方法,就像这样:
FileWriter statFileWriter = new FileWriter(stats, true);
BufferedWriter statsOutput = new BufferedWriter(statFileWriter);
statsOutput.write(Stats.printStat());
statsOutput.newLine();
如果愿意,您也可以在写入统计数据之前添加新行。