2012-09-10 31 views
0

我不熟悉Java,我在将一系列随机数写入输出文件时遇到了一些问题。我需要使用RandomAccessFile和writeDouble。这里是我的代码的任何想法为什么发生这种情况。由于编译错误 - 在Java上使用outputStream

private static void numGenerator(int values){ 
    Random generator = new Random(); 
    for (int i = 0; i < values; i++) { 
     double number = generator.nextInt(200); 
     System.out.println(number); 
     String outFile = "output.txt"; 
     RandomAccessFile outputStream = null; 
     try{ 
      outputStream = new RandomAccessFile(outFile,"rw"); 
     } 
     catch(FileNotFoundException e){ 
      System.out.println("Error opening the file " + outFile); 
      System.exit(0); 
     } 
     number = outputStream.writeDouble(number); //ERROR 
    } 
} 

编辑: 错误:类型不匹配:不能从虚空转换为加倍

回答

3

错误是有道理的。您正在写入RAF,并根据其API writeDouble方法返回void。你为什么要设置一个等于这个的数字?这种说法是没有意义的:

number = outputStream.writeDouble(number); 

,而不是仅仅做:

outputStream.writeDouble(number); 

另外,为什么创建一个新的RAF与循环的每个迭代?难道你不是想在for循环之前创建一个文件并在循环内部添加数据吗?

另外,为什么要使用RAF开始?为什么不简单地使用文本文件?那我跳出

+0

我试图让随机数生成并将它们复制到文件 – JProg

+0

你正在用writeDouble做到这一点。 –

+2

但它不是一个文本文件**它是一个字节文件。我猜你可能会在这里使用随机访问文件来弄错。 –

2

三两件事:

  1. 您使用nextInt()代替nextDouble()
  2. 您的IO操作不在try...catch块内。对抛出任何异常的任何方法的任何调用必须位于try...catch块内。 (或者,如果您使用的方法有签名throws Exception,那么try...catch块是不必要的,但在某处,您需要处理该异常,如果/当它被抛出时。)
  3. The return value of any of the write methods in RandomAccessFile are void.您将无法使用在一个变量中捕获它。
+0

一些伟大的建议! 1+ –