Search code examples
javafile-iousbtext-filesusb-flash-drive

Relative vs Absolute Paths Java


I have a programming mini competition tomorrow and we will be required to create our program on a flash drive given. The judges won't edit our code so it runs and I am worried that the flash drive letter will change and then my program won't be able to locate the text file it needs to read in.

I have always used paths for my flash drive like this:

FileReader file = new FileReader("E:/BPA/Crypto/input.txt");

Is there a way for me to guarantee my program will be able to read in the text file despite if the letter name for my flash drive isn't the same on the judges computer as it was on mine? Thanks!


Solution

  • You may

    1. Put the file inside your sources
    2. Use Class.getResourceAsStream(String name) to get InputStream of the file

    For example, if you have class x.y.z.A

    1. Copy input.txt to src folder into x/y/z package
    2. Get corresponding InputStreamReader as InputStreamReader fileStream = new InputStreamReader(A.class.getResourceAsStream("input.txt"));