完全爲我工作在我的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();
}
}
}
}
如果它實際上是OutputStreamWriter的錯誤,那麼在您自己的代碼中沒有「修復」。 此外,println過載,可以採取一倍,沒有必要做+「」的東西。 – 2012-07-25 00:00:34
請發出堆棧跟蹤 – Bohemian 2012-07-25 00:00:39
您使用IBM的jdk嗎? – 2012-07-25 00:03:56