0

by running this...

File file = new File("Highscores.scr");

i keep getting this error, and i really don't know how to get around it. the file is currently sitting in my source packages with my .java files. I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program. this question isnt about reading the text file but rather specifying its location without using an absolute path . ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path". id post an image to make it more clear but i dont have the 10 rep to do so :/ how do i do this?

cheers.

Joe
  • 45
  • 1
  • 5

4 Answers4

1

The best way to do this is to put it in your classpath then getResource()

package com.sandbox;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Sandbox {

    public static void main(String[] args) throws URISyntaxException, IOException {
        new Sandbox().run();
    }

    private void run() throws URISyntaxException, IOException {
        URL resource = Sandbox.class.getResource("/my.txt");
        File file = new File(resource.toURI());
        String s = FileUtils.readFileToString(file);
        System.out.println(s);
    }


}

I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.

Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).

BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 1
    used InputStream file = getClass().getResourceAsStream("/Highscores.scr"); it worked beautifully! THANKS tieTYT!! – Joe Jun 03 '13 at 09:42
0

As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.

-Project/
 ----src/
 ----test/
-Highscores.scr
Oneb
  • 375
  • 1
  • 10
  • 21
0

If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.

Ketan Bhavsar
  • 5,338
  • 9
  • 38
  • 69
0

You can try to run the following sample program to check which is the current directory your program is picking up.

File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());