1

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!

2 Answers2

3

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"));
Anton Dovzhenko
  • 2,399
  • 11
  • 16
0

If you aren't sure what drive the file will be you could do something like this

    char drive = 'A';
    String filePath = ":/BPA/Crypto/input.txt";
    while(drive != 'Z')
    {
        try{
            Scanner readFromFile = new Scanner(new File(drive + filePath));
            readFromFile.close(); //add this if you simply want the path or drvie letter
            break;
        }catch(FileNotFoundException error)
        {
            System.out.println("Drive: " + drive + " did not contained file in " + drive + filePath);
        }
        drive += 1;
    }

Basically the idea is to attempt to open the file for reading from different drives starting at A up until Y. Obviously you can go further but I am going to assume that drives A-Y would safely exhaust all the possible drives on where ever you are running your software.

By the time you get our of the While loop the variable "drive" will contain the correct letter of the drive you want. You can modify it to be a function that returns the letter, or perhaps the file path, or simply use it once whenever you try to read from the text file. Up to you.

RAZ_Muh_Taz
  • 4,059
  • 1
  • 13
  • 26