NPE when using Filewriter

Hey.

I would like to write process data to a JSON file, for this I use JSONObject and FileWriter, my problem is that when I reach the line:
61 fileWriter.write(object.toJSONString());
I get NPE, the most interesting thing is if I test this code (to write a file) not in wpilib, then everything works fine, but if I add the same code to RobotInit, then everything breaks.
My code is in the photo:

 @Override
public void robotInit() {
    // Instantiate our RobotContainer.  This will perform all our button bindings, and put our
    // autonomous chooser on the dashboard.
    robotContainer = new RobotContainer();

    JSONObject object = new JSONObject();
    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter("C://Users/user/Downloads/navxmxp-master/navxmxp-master/roborio/java/roboJ/src/main/java/Files/info.json",true);
    } catch (IOException e) {
        e.printStackTrace();
    }


    object.put("test","test");
    try {
        fileWriter.write(object.toJSONString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This might be a valid file path on Windows, but not when executing under Linux on the roboRIO.
You should see an error messages from the e.printStackTrace(); in the console window.

1 Like

On the RIO, you can use this to get the name/path to a file:

        File file = new File(Filesystem.getDeployDirectory(), "my_file.json");

The file will end up in /home/lvuser/deploy on the RIO.
On Windows, it will be the src/main/deploy folder in the source tree.

2 Likes

I think you’re right, I’ll try this when I’m in college.

For what it’s worth, the way the original code caught the exception from an inaccessible file and then still tried to write isn’t optimal. Likewise, when you can’t open the file, there’s nothing to close, so fileWriter.close() would actually cause another null pointer exception.
This would overall be shorter and handle those cases:

public void robotInit() 
{
    File file = new File(Filesystem.getDeployDirectory(), "my_file.json");
    try (FileWriter writer = new FileWriter(file, true))
    {
        JSONObject object = new JSONObject();
        object.put("test","test");
        writer.write(object.toJSONString());
    }
    catch (Exception e)
    {
        System.err.println("Cannot write " + file);
        e.printStackTrace();
    }
}

The ‘try-with-resources’ will automatically close the writer, if we were able to open it.
In case of a problem opening the file, or writing to is, the exception will be handled by showing which file we tried to write, followed by detail what exactly failed.

1 Like