![](/img/trans.png)
[英]Trying to create a HashMap after reading data from file. Getting null values. What am I doing wrong?
[英]Trying to write the data to a .txt file. What am I doing wrong?
我想將數據(函數運行所需的時間)寫入.txt文件,以便將其帶到Excel並制作電子表格(可以在Excel中創建對數圖和半對數圖)。
到目前為止,這是我所擁有的:Timing.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();
}
...
}
秒表
/**
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文件中,但是我不希望看到此文本。
是否關閉文件和/或顯式刷新文件? 否則,程序終止時,您的數據可能會被緩沖但未被寫入。
除非您刪除周圍的字符,否則可能一直有效,因為您已經生成了足夠的文本來自動觸發文件寫入。
FileWriter fw2 = new FileWriter(logFile, true);
在這里,您創建了一個名為logFile
的文件。
// if file doesnt exists, then create it
if (!logFile.exists()) {
logFile.createNewFile();
System.out.println("doesn't exist");
}
在這里,您已經用另一個覆蓋了它。 如果您使用的是Unix,Linux等, fw2
將繼續寫入前一個文件,但是該文件已被刪除,因此您將永遠看不到數據。 刪除整個塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.