0

I'm currently reading a txt file in Java, which is located in a package with the scanner object.

To receive the file location I use a quick and dirty method:

File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";  
  • Is there a better way of doing so?

I'd love to improve my code.

Greetings J

JSt
  • 799
  • 2
  • 10
  • 21

2 Answers2

0

Use a URL

URL resource = getClass().getResource("/path/to/text/file.txt");  

As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside

com.myproject.files 

package, your path should be

"/com/myproject/files/myfile.txt"

(mind the leading slash. It's necessary)

Now you can create a File using the URL

new File(resource.getFile());

The "resource.getFile()" returns the absolute path to the file also.

Hope this helps

Janith Jeewantha
  • 185
  • 2
  • 12
0

Get current diretory path

String currentDirPath = System.getProperty("user.dir");

String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";

User home directory

String homePath = System.getProperty("user.home");
Eknath
  • 624
  • 4
  • 11