创建文件并写入它(空指针)

时间:2016-12-13 03:22:36

标签: java

我想创建一个从文件中读取的方法,然后创建一个文件,然后写入从中读取的内容的某个子集,但我在output.write(line)处得到一个空指针异常,我不确定为什么呢?

public void readCreateThenWriteTo(String file, String startRowCount, String totalRowCount) {
        BufferedReader br = null;       
        File newFile = null;
        BufferedWriter output = null;
        StringBuilder sb = null;
        int startRowCountInt = Integer.parseInt(startRowCount);
        int totalRowCountInt = Integer.parseInt(totalRowCount); 

        try {
            br = new BufferedReader(new FileReader(file));
            sb = new StringBuilder();
            newFile = new File("hiya.txt");
            output = new BufferedWriter(new FileWriter(newFile)); 
            String line = "";
            int counter = 0;           

            while (line != null) {          
                line = br.readLine();

                if (startRowCountInt <= counter && counter <= totalRowCountInt) {
                    System.out.println(line);
                    output.write(line);                 
                }
                counter++;
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.info("File was not found.");
            e.printStackTrace();
        } finally {
            // Should update to Java 7 in order to use try with resources and then this whole finally block can be removed. 
            try {
                if ( br != null ) {
                    br.close();
                }               
                if ( output != null ) {
                    output.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                LOGGER.info("Couldn't close BufferReader.");
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

您需要在进入循环之前检查readLine() 的结果:

while ((line = br.readLine()) != null) {
    if (startRowCountInt <= counter && counter <= totalRowCountInt) {
        System.out.println(line);
        output.write(line);                 
    }
    counter++;
}