【问题标题】:What is the proper way to reopen a file in java?在java中重新打开文件的正确方法是什么?
【发布时间】:2012-11-10 18:44:39
【问题描述】:

我已经解决这个问题好几天了,但无法解决。问题要求我打开一个文件并计算平均值然后关闭它。然后重新打开它并计算标准偏差。我遇到的麻烦是在我计算平均值并关闭文件之后。当我尝试重新打开时,它显示找不到文件的错误。这是我目前所拥有的:

File fr = new File(filename);
Scanner inputFile = new Scanner(fr);

filename = inputFile.nextLine();

while(inputFile.hasNext())
{
    double number = inputFile.nextDouble();
    sum =  number + sum;

    count++;

    line = inputFile.nextDouble();
}
inputFile.close();
mean = sum / count;

//New File

File file = new File(filename);
Scanner br = new Scanner(file);

double sumB = 0;
int countB = 0;

filename = br.nextLine();
while(br.hasNext())
{
    double sumthin = br.nextDouble();
    difference =  sumthin - mean;
    sumB = sumB + Math.sqrt(difference);
    count++;
    line = br.nextDouble();
}
br.close();
Math.sqrt(sumB / count);

【问题讨论】:

  • 错误是什么?你为什么不使用fr(第二次)?
  • 这是显示的错误:Exception in thread "main" java.io.FileNotFoundException: 87.5517 (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at StatsDemo.main(StatsDemo.java:50)
  • 如果我使用fr,它会给我一个错误,说它已经定义了
  • 不声明,直接使用。新扫描仪(法国)
  • 考虑到您可以一次计算均值和标准差。如果这不是家庭作业,这可能是一种更有效的方法。

标签: java file-io printwriter


【解决方案1】:

您(可能)没有打开同一个文件两次 - 您正在从第一个文件中读取文件名,然后打开第二个文件:

File fr = new File(filename);
...
filename = inputFile.nextLine();
...
File file = new File(filename);

【讨论】:

    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 2011-10-12
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2020-10-12
    相关资源
    最近更新 更多