gpt4 book ai didi

java - 尝试编写一个使用 OutputStream 写入文本文件的循环

转载 作者:行者123 更新时间:2023-11-29 06:21:43 24 4
gpt4 key购买 nike

我不是java程序员,我是VB程序员。我这样做是作为作业的一部分,但是,我并没有在与作业相关的事情上寻求帮助。我想弄清楚如何让 OutputStreamWriter 在这种情况下正常工作。我只想捕获我生成的值并将它们放入文本文档中。该文件已生成,但只存在一个条目,而不是我期望的 40 个条目。我可以用 VB 在心跳中做到这一点,但现在 java 对我来说感觉很陌生。感谢您的帮助。

谢谢,

史蒂夫

代码如下:

  public static void main(String[] args) {
long start, end;
double result,difference;

try {
//OutputStream code assistance from
// http://tutorials.jenkov.com/java-io/outputstreamwriter.html
OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt");
Writer out = new OutputStreamWriter(outputStream);

for(int n=1; n<=20; n++) {
//Calculate the Time for n^2.
start = System.nanoTime();

//Add code to call method to calculate n^2
result = mN2(n);
end = System.nanoTime();
difference = (end - start);

//Output results to a file
out.write("N^2 End time: " + end + " Difference: " +
difference + "\n");
out.close();
}
} catch (IOException e){
}

try {
OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt");
Writer out = new OutputStreamWriter(outputStream);

for(int n=1; n<=20; n++){
//Calculate the Time for 2^n.
start = System.nanoTime();
//Add code to call method to calculate 2^n
result = m2N(n);
end = System.nanoTime();
difference = (end - start);
//Output results to a file
out.write("N^2 End time: " + end + " Difference: " + difference + "\n");
out.close();
}
} catch (IOException e){
}
}

//Calculate N^2
public static double mN2(double n) {
n = n*n;
return n;
}

//Calculate 2N
public static double m2N(double n) {
n = 2*n;
return n;
}

最佳答案

您正在循环中关闭文件。下一次在循环中您将尝试写入已关闭的文件,这将引发异常...但是在您捕获 IOException 的地方您有一个空 block ,这将有效地忽略异常。

尝试将 out.close() 调用移动到 finally block 中,如下所示:

try {
...
}
catch ( IOException e) {
// Log any errors
}
finally {
out.close();
}

关于java - 尝试编写一个使用 OutputStream 写入文本文件的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2756170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com