Search code examples
javatext

java reading text from src without writing a long path


I can read texts and write them to console however when i install this application to another computer wherever it is installed I dont want to change the path of the txt file. I want to write it like

BufferedReader in = new BufferedReader(new FileReader("xxx.txt"));

I don't want to:

BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\abcde\\Desktop\\xxx.txt"));

is there any way to show this txt file? By the way I put this txt file inside the sources but it cant read!


Solution

  • First get the default application path then check if file exist if exist continue if not close application.

     String path = System.getProperty("user.dir");
          System.out.println(path + "\\disSoruCevap.txt");
          File file = new File(path + "\\disSoruCevap.txt");
    
    
          if (!file.exists()) {
              System.out.println("System couldnt file source file!");
              System.out.println("Application will explode");
          }
    

    EDIT*

    Please prefer one of the answer using resource streams, as you will see from comments using user.dir is not safe in every case.