0

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
Routray
  • 75
  • 1
  • 12
  • 1
    Share the stack trace. – Rakesh KR Jul 25 '19 at 08:42
  • Can you share the stack trace – Rajendra Gupta Jul 25 '19 at 08:45
  • updated log file – Routray Jul 25 '19 at 09:07
  • 1) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 2) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Hard code data to replace the DB. 3) `// handle exception` No! `e.printStackTrace();` is shorter & more useful. Never comment on handling exceptions as a 'to do' task. Handle them ***right now.*** – Andrew Thompson Jul 25 '19 at 13:55

2 Answers2

0

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/

cameron1024
  • 9,083
  • 2
  • 16
  • 36
0

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks for the response. I have updated the code based on ur comment, but still facing the same issue. Can you please have a look on the mail code, what wrong i am doing here. Updated parent code. – Routray Jul 25 '19 at 09:28
  • 1
    Unfortunately your comment is vague and there isn't much I can say/edit based on it. – Tim Biegeleisen Jul 25 '19 at 09:30