---
title: "How do you read a file from the classpath in Java?"
description: "Load resources packaged with your app using getResourceAsStream, not File. Learn the leading slash rule and how to read the text from the stream."
url: "https://bugsee.com/answers/java/java-read-file-from-classpath/"
---

# How do you read a file from the classpath in Java?

Use `getClass().getResourceAsStream("/config.properties")` and read the stream. A file in the classpath is not a `File` on disk once the app is packaged as a JAR.

```java
try (InputStream in = Main.class.getResourceAsStream("/config.properties")) {
    if (in == null) throw new FileNotFoundException("config.properties not on the classpath");

    String text = new String(in.readAllBytes(), StandardCharsets.UTF_8);   // Java 9+

    Properties props = new Properties();
    // props.load(in) could be used instead of reading the text
}

// Class loader version: no leading slash, always relative to the classpath root
InputStream in2 = Thread.currentThread().getContextClassLoader()
        .getResourceAsStream("config.properties");
```

- With Maven or Gradle, put the file under `src/main/resources`.
- `Class.getResourceAsStream` treats a path without a leading slash as relative to the class's package; a leading slash starts at the classpath root.
- Avoid `new File(url.getPath())`, which works in the IDE and fails inside a JAR.

## Related questions

- [How do you fix java.nio.file.NoSuchFileException?](https://bugsee.com/answers/java/java-nio-file-nosuchfileexception/)
