Skip to main content
查利博客

Java FileInputStream Example

The Java java.io.FileInputStream class is used to read raw bytes from a file. It extends the java.io.InputStream class. For reading character streams, it is recommended to use the java.io.FileReader class.

Read a Properties File #

public class FileInputStreamExample {
  public static void main(String[] args) {
    Properties aProperties = new Properties();
    try {
      System.out.println(System.getProperty("user.dir"));
      aProperties.load(new FileInputStream("test.properties"));
      System.out.println(aProperties.getProperty("me"));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

test.properties:

me=caizhenhua

Output:

caizhenhua

Absolute and Relative Path #

For UNIX System, if slash / is given in the filename string, then it is considered as an absolute path. Otherwise, the full path is composed of the current working directory and the filename. The current working directory is at which the Java application was being started. It is a java system property and the corresponding key value is user.dir. In general, using FileInputStream to load properties files is not a good practice.

Read File from Classpath #

A better way to load properties files by using the java.lang.ClassLoader class:

public class ReadFileFromClasspath {
  public static void main(String[] args) {
    String[] arrayOfClasspaths = System.getProperty("java.class.path").split(":");
    for (String str : arrayOfClasspaths) {
      System.out.println(str);
    }
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream("application.properties");
    Properties aProperties = new Properties();
    try {
      aProperties.load(is);
    } catch (IOException e) {
      e.printStackTrace();
    }
    System.out.println(aProperties.getProperty("caizhenhua"));
  }
}

application.properties:

caizhenhua=me

Output:

me