java - 为什么空异常运行时错误出现在 line `outputFile.println("Package : "+ letter);` ?

标签 java runtime-error filewriter printwriter argumentnullexception

我的代码当前已编译并运行。然而,当程序到达 outputFile.println("Package: " + letter); 行时,程序崩溃了。为什么 outputFile.println("Package: " + letter);及其他outputFile.println("");导致程序崩溃并且不打印到文件dataFile ?是dataFile甚至在 try-catch block 执行时被创建?

import java.util.Scanner;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.lang.NullPointerException;
import java.io.*;

public  class Lab5backup
{
    public static void main (String[] args) {
        Scanner keyboard = new Scanner(System.in);
        NumberFormat fmtCurr = NumberFormat.getCurrencyInstance();

        System.out.print("Data file of prior internet usage: ");
        String dataFile = keyboard.nextLine();

        File file = null;           
        Scanner openFile = null;        
        FileWriter writeFile = null;    
        PrintWriter outputFile = null;  

        boolean invalid;
            try {
                openFile = new Scanner(file);
                writeFile = new FileWriter(dataFile, true);
                outputFile = new PrintWriter(writeFile);
                invalid = false;
            }
            catch (FileNotFoundException fnfe) {
                System.out.print("No such file exists; creating it.\n");
                invalid = true;
            }
            catch (NullPointerException npe) {
                System.out.print("No such file exists; creating it.\n");
                invalid = true;
            }
            catch (IOException ioe) {
                invalid = true;
            }

        File inFile = new File(dataFile);

        if (inFile.exists()) {
            averageHours = openFile.nextDouble();
            averagePaid = openFile.nextDouble();
            totalPaid = openFile.nextDouble();
            System.out.println("Usage history: ");
            System.out.println("  Average Hours Used: " + averageHours);
            System.out.println("  Average Paid: " + averagePaid);
            System.out.println("  Total Paid: " + fmtCurr.format(totalPaid));
        }
           //create and validate variables here
           //taken out of example because not important to question

            outputFile.println("Package: " + letter);

            if (openFile.hasNextDouble()) 
                averageHours = ((hours + openFile.nextDouble())/numOfHourInputs++);
            outputFile.println("Hours: " + hours);

            if (openFile.hasNextDouble())
                averagePaid = ((charge + openFile.nextDouble())/numOfCharges++);
            outputFile.println("Charge: " + charge);    
            outputFile.println("Average Hours: " + averageHours);
            outputFile.println("Average Paid: " + averagePaid);
            totalPaid += charge;
            outputFile.println("Total Paid: " + totalPaid);

            openFile.close();
            outputFile.close();

    } //end of main method
}

最佳答案

当您将 file 变量传递到此行的扫描器构造函数时,该变量为 null:

openFile = new Scanner(file);

此行将引发 NullPointerException,因为参数不能为 null,以便扫描器正确初始化。

代码中的扫描仪openFile似乎引用了代码中未直接指定的其他文件。鉴于此,我假设您正在尝试将用户传递的文件(表示为 dataFile)加载到扫描仪中进行处理。为此,您可以使用采用字符串文件名/路径名的 File 构造函数。

新文件的 Javadoc(字符串路径名):

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

将其应用到您的代码中:

Scanner keyboard = new Scanner(System.in);
NumberFormat fmtCurr = NumberFormat.getCurrencyInstance();

double averageHours = 0;
double averagePaid = 0;
double totalPaid = 0;

System.out.print("Data file of prior internet usage: ");
String dataFile = keyboard.nextLine();

File file = new File(dataFile);

// Your code continued below...

注意:您似乎已经对文件变量 inFile 执行了此操作。我建议您要么将该声明移至顶部(并将其传递到 openFile 扫描器中),要么完全删除它并在其余代码中使用您的 file 对象.

关于java - 为什么空异常运行时错误出现在 line `outputFile.println("Package : "+ letter);` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28512203/

相关文章:

java - GAE 1.7.2 的套接字连接错误

c# - 创建编译错误而不是运行时错误

java - 尝试在 Java 中使用 hasNext 时出现错误

java - OpenCV:在没有校准图像的情况下估计径向失真

java - 如果我只想测试 JdbcTemplate 代码,@DataJpaTest 的等效项是什么?

java - Gridbaglayout、Insets或anchor不会生效

Java - Android SDK - 不幸的是<项目名称>发生了崩溃错误

c++ - 在 Qt/QML 中的每一帧更新图像时运行时崩溃

java - 使用 Java 将二进制 PGM 文件转换为 ASCII PGM 文件?使用 FileWriter 给出空文件

Java - 使用 Scanner 在 FileWriter 中命名文件