我一直在线程" main"中得到异常。显示java.lang.NullPointerException'

时间:2017-10-06 02:52:58

标签: java io nullpointerexception

错误与writeToFile()方法有关。我可以将它注释掉,并且在没有异常错误的情况下运行完美。所以基本上,我试图将这些营养成分打印在文本文件上。 错误看起来像这样

  

"线程中的异常" main" java.lang.NullPointerException at   Environment.writeToFile(Java1001.java:71)at   环境。(Java1001.java:54)at   Java1001.main(Java1001.java:43)"

 import static java.lang.System.*;
    import java.io.*;

    public class Java1001
    {
        public static void main(String[] args) throws IOException
        {
            new Environment();
        } 
    }

    class Environment
    {
        private PrintStream outFile;

        public Environment()
        {
            createOutputStream();
            writeToFile();
        }

        public void createOutputStream()
        {
            // create outFile stream here
            File outFile = null;
            try
            {
                outFile = new File("Nutrition.txt");
                outFile.createNewFile();
            }
            catch (Exception e){}
        }

        public void writeToFile()
        {
            outFile.println("NUTRITION FACTS");
            outFile.println("======================================");
            outFile.println("Serving Size 1 tbsp (6g)");
            outFile.println("Servings Per Container about 4");
            outFile.println("======================================");
            outFile.println("Amount Per Serving");
            outFile.println("Calories           20");
            outFile.println("Calories from Fat  5");
            outFile.println("======================================");
            outFile.println("Total Fat 0.5g");
            outFile.println("Sodium 280mg");
            outFile.println("Total Carbohydrate 4g");
            outFile.println("Sugars 0g");
            outFile.println("Protein less than 1 g");
            outFile.println("======================================");
        }
    }

1 个答案:

答案 0 :(得分:0)

Johnny Mopp指出,你在createOutputStream方法和outFile实例中都有一个outFile。尝试删除createOutputStream方法中的File outFile = null;,然后在try,write:

中删除
this.outFile = new File("Nutrition.txt");
this.outFile.createNewFile();