简体   繁体   中英

Getting NullPointerException while trying to save console output in text file

Can someone please help here, i am trying to save the console output into a text file, i am getting NullPointerException error. Please suggest what wrong i am doing here.Also is there a way to create a new text file for each run?

Thanks in advance:

import java.io.*;  
import java.sql.*;  

public class RetrieveFile {  
    public static void main(String args[]) throws Exception {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@tkdp2gpsdbc03-vip.hk.hsbc:35120/GPSEAU_TAF", "gppeareadu", "F4nt4na");

            PreparedStatement ps = con.prepareStatement("select * from MSG_FEES where MID='1961108001406E00'");
            ResultSet rs = ps.executeQuery();

            try {
                printResultColumns(rs);
            } catch (SQLException e) {
                System.err.println(e.getMessage());
            }

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printResultColumns(ResultSet resultSet) throws SQLException, IOException {
    ResultSetMetaData rsmd = resultSet.getMetaData();
    int columnCount = rsmd.getColumnCount();

    while (resultSet.next()) {
        // you get a single result row in here, not the entire ResultSet
        for (int i = 1; i <= columnCount; i++) {
            switch (rsmd.getColumnType(i)) {
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
            case Types.CHAR:
                System.out.println(resultSet.getString(i));
                break;
            case Types.DOUBLE:
                System.out.println(resultSet.getDouble(i));
                break;
            case Types.INTEGER:
                System.out.println(resultSet.getInt(i));
                break;
            case Types.DATE:
                System.out.println(resultSet.getDate(i).toString());
                break;
            case Types.TIMESTAMP:
                System.out.println(resultSet.getTimestamp(i).toString());
                break;
            case Types.BOOLEAN:
                System.out.println(resultSet.getBoolean(i));
                break;
            case Types.DECIMAL:
            case Types.NUMERIC:
                System.out.println(resultSet.getBigDecimal(i));
                break;
            default:
                //System.out.println(rsmd.getColumnClassName(i)



            }
        }
    }


StringBuilder record = new StringBuilder();
while (resultSet.next()) {
    if (record.length() > 0) record.append("\n");
    for (int i=1; i < columnCount; ++i) {
        if (i > 1) record.append(", ");
        record.append(resultSet.getInt(i));
    }
}
try {
    String filename = "C:\\Users\\45060849\\Desktop\\test1.txt";
    BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
    char[] str = null;
    writer.write(str);
    writer.close();
}
catch (IOException e) {
    // handle exception
}

} }

Please find the below Log file for above code:- Please find the below Log file for above code:-

java.lang.NullPointerException
    at java.io.Writer.write(Writer.java:127)
    at RetrieveFile.printResultColumns(RetrieveFile.java:76)
    at RetrieveFile.main(RetrieveFile.java:14)
Picked up JAVA_TOOL_OPTIONS: -Duser.home=C:\Users\123

Your error is in the following line:

char[] i = null;
String data = String.valueOf(i);

The method String.valueOf() asserts that any char array given is not null, otherwise a NullPointerException is thrown. You need to set the value of this char[] before calling String.valueOf() on it, otherwise your error will persist.

Note: there are other errors with your code, and other things may fail even if you fix this. Consider reading this page, which details thoroughly how file IO should be done in Java: https://docs.oracle.com/javase/tutorial/essential/io/

You are currently trying to write a null char[] to a text file, hence the null pointer exception. Assuming you just want to write out each record, you could try:

StringBuilder record = new StringBuilder();
while (resultSet.next()) {
    if (record.length() > 0) record.append("\n");
    for (int i=1; i < columnCount; ++i) {
        if (i > 1) record.append(", ");
        record.append(resultSet.getObject(i));
    }
}
try {
    String filename = "C:\\Users\\2345\\Desktop\\test2.txt";
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(record);
    writer.close();
}
catch (IOException e) {
    // handle exception
}

The trick here is to just use ResultSet#getObject() to obtain the value for each column, in each row. Then, just rely on the toString() method to render the actual value.

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