0
reader = new Scanner(Paths.get(userDirectory + "/src/file.txt"));

my txt file is on src and program runs normally in IDE but jar file can't read my txt file how can i solve this problem.

  • 2
    You can read the file by providing the full/absolute path in the code like `/your/dir/src/file.txt` or use the classloader to get the file path like: `String filePath = getClass().getClassLoader().getResource(fileName).getFile()` and then use the derived filePath – Vini Dec 30 '22 at 08:03
  • Please check this question: https://stackoverflow.com/questions/3369794/how-to-read-a-file-from-jar-in-java – tostao Dec 30 '22 at 08:08

1 Answers1

0

I didn't get same problem, but I don't know What are you using for "userDirectory".

public class Main {
public static void main(String[] args) throws IOException {
    String userDirectory = "/home/ubuntu/Desktop/Personal/testjarcreate";
    Scanner reader = new Scanner(Paths.get(userDirectory + "/src/file.txt"));
    System.out.println(reader.next());
}

} The content are "test,test" in file.txt's. When it build with this main, I get "test,test" result on terminal.

nietzsche
  • 21
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '22 at 13:29