Home>

There is a simple program in which I read information from a file usingFileInputStream... The file is located in the root directory of the project, at the level with out and src, when the project is started in IntellijIDEAeverything works fine. But as soon as I run the createdjar, the program works fine, but for some reason the program starts looking for this file in the Windows user folder. How to make it so that the files are taken from the folder withjar? To access the file, I use the following construction:

FileInputStream fin= new FileInputStream ("input.txt");

Thanks in advance for your reply)

Is it possible to read a file from a jar file using FileInputStream? Look towards the getResourceAsStream method.

Suvitruf - Andrei Apanasik2021-02-23 18:35:35
  • Answer # 1
    1. If fileinput.txtis inside the JAR, you need to read it throughgetResourceAsStream ()
    2. If the file is outside the JAR, thenFileInputStream ()will look for it in working directorywhich may depend on the OS, variations are:
      • current directory -where the JAR is running from
      • home directory

    In order to read from the directory where the JAR itself is located, you need to do one of 2:

    • run JAR from the directory where it is located (in the code, you must specify the path'./input.txt)
    • in the code, specify the directory where to read through:new File (MyClass.class.getProtectionDomain (). getCodeSource (). getLocation () .toURI ()). getPath ();-whereMyClass-one of the classes that is packed inside the JAR