【发布时间】:2015-11-29 22:40:12
【问题描述】:
我想将数据(函数运行所需的时间)写入 .txt 文件,以便我可以将其带到 Excel 并制作电子表格(可以在电子表格)。
这是我目前所拥有的: 计时.java
public static void main(String args[]) {
Stopwatch timeMe = new Stopwatch();
...
try
{
File logFile = new File("log.txt");
FileWriter fw = new FileWriter(logFile2, true);
FileWriter fw2 = new FileWriter(logFile, true);
BufferedWriter bw = new BufferedWriter(fw);
// if file doesnt exists, then create it
if (!logFile.exists()) {
logFile.createNewFile();
System.out.println("doesn't exist");
}
...
for (int i = 1000; i <= 256000; i+=1000)
{
int[] randomArray = randomarr(i);
fw.write(String.valueOf(i));
fw.write(String.format("%n"));
timeMe.start();
pluto(randomArray);
timeMe.stop();
fw.write(timeMe.toString());
fw.write(String.format("%n"));
}
}
catch (IOException e)
{
e.printStackTrace();
}
...
}
Stopwatch.java
/**
A class to measure time elapsed.
*/
public class Stopwatch
{
private long startTime;
private long stopTime;
public static final double NANOS_PER_SEC = 1000000000.0;
/**
start the stop watch.
*/
public void start()
{ System.gc();
startTime = System.nanoTime();
}
/**
stop the stop watch.
*/
public void stop()
{ stopTime = System.nanoTime(); }
/**
elapsed time in secods.
@return the time recorded on the stopwatch in seconds
*/
public double time()
{ return (stopTime - startTime) / NANOS_PER_SEC; }
public String toString()
{ return "elapsed time: " + time() + " seconds."; }
/**
elapsed time in nanoseconds.
@return the time recorded on the stopwatch in nanoseconds
*/
public long timeInNanoseconds()
{ return (stopTime - startTime); }
}
问题是,当我在秒表中更改任何内容时,即删除“经过时间:”和“秒”。在 .toString() 方法中隔离数字,不会打印到文件中。换句话说,.txt 文件是空的。当我使用原始的 Stopwatch.java 文件运行它时,所有内容都会打印到 log.txt 文件中,但我不想要这个文本。
【问题讨论】:
-
为什么会有两个文件?你为什么不写信给第二个?为什么你把名字弄混了
fw = logfile2和反之亦然?