写入文件java错误

时间:2014-02-08 02:51:39

标签: java file-io

当我尝试将信息写入文件时,我收到NullPointerException。任何人都可以帮我看看出了什么问题吗?

    else if(response == 4){
            System.out.println("Enter the name of the file to save items to: ");
            saveFile = input.nextLine();

            try {outfile = new PrintWriter(new FileWriter(saveFile+".txt"));}
            catch (IOException err) {
                outfile = null;
                System.out.println("Error writing to file\n");

            }
            for (int i = 0; i < items.length; i++) {

                outfile.print(items[i].getType() + "\n" + items[i].getName() + "\n" + items[i].getDescription() + "\n" + items[i].getCalories() + "\n" + items[i].getItemSpecifics());
            }

2 个答案:

答案 0 :(得分:2)

您正在将PrintWriter对象(outfile)设置为null,然后尝试在其上执行print方法。

这就是你获得NullPointerException

的原因

检查文档,您可以发现抛出IOException的人实际上是FileWriter构造函数。

Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

所以,这可能是你的问题。如果没有,您可以尝试像这样创建它,您不需要FileWriter部分:

outfile = new PrintWriter(saveFile+".txt");

我已经在我的计算机上测试了两种方式,但它确实有效。

另外,记得在完成文件写入后调用close()方法,否则不会修改它。

答案 1 :(得分:0)

您粘贴的代码中可能有几个地方NullPointerException

  1. 在捕获异常时调用outfile = null,然后在它为空时尝试使用它。
  2. 当您拨打input 时,
  3. input.nextLine()可能为null 致电items
  4. 时,
  5. items.length可能为null 致电items[i]
  6. 时,
  7. items[i].getType()可能为null

    没有完整的堆栈跟踪很难说 - 调试它会是你最好的选择。异常也可能发生在此处调用的其他函数之一(getCalories()等)

相关问题