mbmast
mbmast

Reputation: 1100

Java File.createTempFile() throws NullPointerException

This Java 1.8.0_102 program:

import java.io.File;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        File tempFile = null;

        try {
            tempFile = File.createTempFile(null,  null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Throws this exception:

Exception in thread "main" java.lang.NullPointerException
    at java.io.File.createTempFile(Unknown Source)
    at java.io.File.createTempFile(Unknown Source)
    at Main.main(Main.java:10)

According to the Javadocs, both arguments may be null. Any idea why this particular exception is being thrown?

Upvotes: 2

Views: 4615

Answers (3)

BrainFRZ
BrainFRZ

Reputation: 407

According to the error output, the exception is NullPointerException. However, according to the Javadocs for File.createTempFile, that is not a thrown exception. That means something unexpected is going on with your code. We can see the source code to see exactly what's going on (keep in mind the third parameter, directory is null because you used the overloaded version).

The very first thing it does is check to see the length of prefix and make sure that it's not less than 3 (on line 2000). However, since your value for prefix is null, checking length() on it will always return a NullPointerException because you can't call any methods on a null object. The fact that it didn't even get to throw the InvalidArgumentException is further evidence that it died in the if-check. We also can see both in the Javadoc and the source code that it requires prefix to be a String with 3 characters. Interestingly, in Java 6, this method did throw a NullPointerException explicitly if prefix was null.

Upvotes: 0

M S
M S

Reputation: 129

The java doc says "prefix The prefix string to be used in generating the file's name; must be at least three characters long". Precisely why it is throwing null pointer exception. Here is the link File java doc

Upvotes: 1

Paweł Chorążyk
Paweł Chorążyk

Reputation: 3643

Prefix cannot be null according to JavaDoc

Parameters:

prefix - The prefix string to be used in generating the file's name; must be at least three characters long

suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used

Upvotes: 3

Related Questions