chinabugotech/hutool · error · NullPointerException

File uri is null!

Error message

File uri is null!

What it means

FileUtil.file(URI) constructs a File from a URI. If the URI is null it throws NullPointerException("File uri is null!") instead of letting new File(null) fail later. This is an explicit null precondition guard.

Source

Thrown at hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java:380

		for (String name : names) {
			if (file == null) {
				file = file(name);
			} else {
				file = file(file, name);
			}
		}
		return file;
	}

	/**
	 * 创建File对象
	 *
	 * @param uri 文件URI
	 * @return File
	 */
	public static File file(URI uri) {
		if (uri == null) {
			throw new NullPointerException("File uri is null!");
		}
		return new File(uri);
	}

	/**
	 * 创建File对象
	 *
	 * @param url 文件URL
	 * @return File
	 */
	public static File file(URL url) {
		return new File(URLUtil.toURI(url));
	}

	/**
	 * 获取临时文件路径(绝对路径)
	 *
	 * @return 临时文件路径

View on GitHub (pinned to 8870454b2a)

Solutions

  1. Null-check the URI before calling file().
  2. When the URI comes from getResource(), treat null as 'resource not found' and handle that case explicitly.
  3. Use Objects.requireNonNull(uri, "uri") for an early, clear failure.

Example fix

// before: getResource may return null
File f = FileUtil.file(cls.getResource("/x.txt").toURI()); // NPE

// after
URL url = cls.getResource("/x.txt");
if (url == null) {
    throw new FileNotFoundException("/x.txt");
}
File f = FileUtil.file(url.toURI());
Defensive patterns

Strategy: validation

Validate before calling

if (uri == null) {
    throw new IllegalArgumentException("uri must not be null");
}
File f = FileUtil.file(uri);

Type guard

static boolean isResolvableUri(URI uri) {
    return uri != null && uri.getScheme() != null;
}

Try / catch

try {
    return FileUtil.file(uri);
} catch (NullPointerException e) {
    // uri was null: handle missing-resource case
}

Prevention

When it happens

Trigger: Calling FileUtil.file((URI) null).

Common situations: Passing the result of ClassLoader.getResource().toURI() when the resource was not found (getResource returns null); a URI parsed from bad input that came back null; conditional code that left the URI unassigned.

Related errors


AI-assisted analysis of chinabugotech/hutool@8870454b2a (2026-08-14). Data as JSON: /api/errors/27a64bcddb9ddf80. Report an issue: GitHub.