我的空间有问题。如何正确打印输出文件?当我运行我的代码时,就像。。。。。
这就是我的主方法的样子,并生成输出文件。。。。。
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
如果我在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.
如何在没有额外行的情况下打印输出,并正确打印?
将主方法更改为:
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();
从stats.createNewFile()
返回的Boolean fromStart
将是:
true
如果是第一次创建文件-->则无需添加额外的换行符false
(如果文件已经存在)-->在写入新内容之前需要添加新行
您需要在末尾附加额外的"\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;
}
}
在主方法中,只需使用BufferedWriter
的newLine()
方法,如下所示:
FileWriter statFileWriter = new FileWriter(stats, true);
BufferedWriter statsOutput = new BufferedWriter(statFileWriter);
statsOutput.write(Stats.printStat());
statsOutput.newLine();
如果你愿意,你也可以在写统计数据之前添加一行新行。