使用printwriter编辑文件

时间:2016-04-13 05:05:35

标签: java file printwriter

当我第一次运行此代码时,我没有问题 但是当用已经存在的文件再次运行它时 并在此文件中添加其他数据 我看到了这个例外

Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:67)

这是第67行

writer.println(proc[j].ID+"\t"+proc[j].name+"\t"+proc[j].Parent+"\t"+proc[j].state);

这是我的代码

import java.util.Scanner;
    import java.io.*;
    public class Main {
        public static void main(String [] args) throws IOException{
            File pro =new File("process.txt");
            Scanner input = new Scanner (System.in);
            int [] ID_Container = new int[10];
            Pro [] proc = new Pro [10] ;
            int memory =1000;
            System.out.println("Enter ID , Name , Parent, State");
            boolean flag =true;

            int i =0;
            while(flag&&i<10){
                System.out.println("please enter the ID");
                int ID=input.nextInt();

                System.out.println("please enter the name");
                String name=input.next();

                System.out.println("please enter the parent");
                int Parent=input.nextInt();

                System.out.println("please enter the State");
                char state=input.next().charAt(0);

                System.out.println("please enter the size");
                int size=input.nextInt();

                if(ID<0||ID>10||ID_Container[ID-1]==1){
                    for (int j = 0; j < 10; j++) {
                        if(ID_Container[j]==0){
                            ID=j+1;
                            System.out.println("Your Id has changed to "+ ID);
                            break;
                        }
                    }
                }

                if(size<memory){
                    proc[i]=new Pro(ID,name,Parent,state,size);
                    ID_Container[ID-1]=1;
                    memory-=size;
                    System.out.println("Do you want to add another process\n1-yes 0-no");
                    int s =input.nextInt();

                    if(s==0)
                        flag= false;
                    i++;
                }
            }
        PrintWriter writer = new PrintWriter(new FileWriter(pro, true));
        writer.println("ID\tname\tparent\tstate");
            for (int j = 0; j < 10; j++) {
                if(ID_Container[j]==0)
                    continue;
                writer.println(proc[j].ID+"\t"+proc[j].name+"\t"+proc[j].Parent+"\t"+proc[j].state);
            }
        writer.close();
        }
    }

    public class Pro {
    int ID;
    String name;
    int Parent;
    char state;
    int size;
    Pro(int ID , String name , int Parent , char state,int size){
        this.ID=ID;
        this.name=name;
        this.Parent=Parent;
        this.state=state;
        this.size=size;
    }
}

1 个答案:

答案 0 :(得分:0)

由于此时抛出异常,因此对于至少一个特定索引,数组必须包含null