简体   繁体   中英

Java BufferedWriter Write method

I am creating a CSV file using BufferedWriter from a ResultSet object. A few of the database columns hold null values.

When I call obj.write(rs.get()) I am getting a NullPointerException when the output is null . Is there any other class other than BufferedWriter which I can use to overcome this.

I do not want to check for null condition on the database columns since there is large number of columns. I am new to Java and tried searching for solution but could not find anything.

You can use a cleverer Buffered writer that performs the nullity check. Here is a code sample that will probably need to be tweaked a bit, I don't currently have a Java compiler available.

public class MyBufferedWriter extends BufferedWriter {
    public void write(String str) {
        if (str==null)
            str="";
        super.write(str);
    }
}

I know this is an old question, but here is a suggestion anyway: Use OpenCSV . The class you want to use is au.com.bytecode.opencsv.CSVWriter

Just solendil 's code, fixed so that it compiles, and formatted a bit:

package mypackage;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;

public class MyBufferedWriter extends BufferedWriter {

    public MyBufferedWriter(Writer out) {
        super(out);
    }

    @Override
    public void write(String str) throws IOException {
        if (str == null)
            str = "";
        super.write(str);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM