我创建了一个写入文件的方法,如下面的代码所示。使用两个给定参数从另一个方法调用此方法 1000 次。
但是,在其中 5 个调用中,此方法捕获错误“e”并打印出: java.lang.ArrayIndexOutOfBoundsException ,在我的终端中,我得到 System.out.println(""+(double)C/的结果T),但在文件中缺少此结果。 (其他调用工作正常)
一开始我真的很困惑,因为我根本不使用数组。经过谷歌搜索后,我发现了这个:http://www-01.ibm.com/support/docview.wss?uid=swg1IZ87600
我仍然很困惑,不知道如何解决这个问题。有人帮忙吗?
public void myMethod(int C, int T) {
try {
FileOutputStream fout = new FileOutputStream ("output.txt", true );
PrintStream ps = new PrintStream(fout);
System.out.println(""+(double)C/T);
ps.println((double)C/T+"");
// close file
fout.close();
}
catch(Exception e) {
System.err.println(e);
}
}
最佳答案
在我的 Windows JVM 上完美运行:
package cruft;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* ArrayIndexOutOfBoundsProblem
* @author Michael
* @link http://stackoverflow.com/questions/11640904/java-lang-arrayoutofbounds-exception-when-writing-to-a-file
* @since 7/24/12 7:58 PM
*/
public class ArrayIndexOutOfBoundsProblem {
public static void main(String[] args) {
ArrayIndexOutOfBoundsProblem aioob = new ArrayIndexOutOfBoundsProblem();
int c = ((args.length > 0) ? Integer.valueOf(args[0]) : 10);
int t = ((args.length > 1) ? Integer.valueOf(args[1]) : 2);
aioob.myMethod(c, t);
}
public void myMethod(int C, int T){
try{
FileOutputStream fout = new FileOutputStream("output.txt", true );
PrintStream ps = new PrintStream(fout);
System.out.println(""+(double)C/T);
ps.println((double)C/T+"");
// close file
fout.close();
}
catch(Exception e)
{
System.err.println(e);
}
}
}
我会这样写:符合Java编码标准并使用更清晰的名称:
package cruft;
import java.io.*;
/**
* ArrayIndexOutOfBoundsProblem
* @author Michael
* @link http://stackoverflow.com/questions/11640904/java-lang-arrayoutofbounds-exception-when-writing-to-a-file
* @since 7/24/12 7:58 PM
*/
public class ArrayIndexOutOfBoundsProblem {
public static void main(String[] args) {
ArrayIndexOutOfBoundsProblem aioob = new ArrayIndexOutOfBoundsProblem();
int c = ((args.length > 0) ? Integer.valueOf(args[0]) : 10);
int t = ((args.length > 1) ? Integer.valueOf(args[1]) : 2);
aioob.printValues(c, t);
}
public void printValues(int c, int t){
printValues(System.out, c, t);
}
public void printValues(String outputFilePath, int c, int t) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFilePath);
PrintStream ps = new PrintStream(fos);
printValues(ps, c, t);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
close(fos);
}
}
public void printValues(PrintStream ps, int c, int t) {
ps.println(String.format("c: %10d t: %10d ratio c/t: %10.4f", c, t, (double) c/t));
}
public static void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
关于java.lang.ArrayOutOfBounds 写入文件时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11640904/