8

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running. Does anyone know the solution to my problem or a better way of reading a text file?

Victor
  • 1,305
  • 2
  • 11
  • 15
  • I'd assume that if input is being passed on as an program arg, you'd like to pass arbitrary input to program. Is that correct? – David J. Liszewski Jul 22 '10 at 14:50
  • Umm not really. Are u talking about methods or functions? Im talking about as a class im passing in a argument and when i run the main method it should read the text file but it doesn't. My code is Scanner sc1 = new Scanner(new File(args[0])); When debugging it couldn't even get pass this line. – Victor Jul 22 '10 at 15:17

7 Answers7

9

Do not use relative paths in java.io.File.

It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.

Always use absolute paths in java.io.File, no excuses.

For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:

public MyClass() {
    URL url = getClass().getResource("filename.txt");
    File file = new File(url.getPath());
    InputStream input = new FileInputStream(file);
    // ...
}

or

public MyClass() {
    InputStream input = getClass().getResourceAsStream("filename.txt");
    // ...
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You can specify the working directory in Eclipse. It is in the dialog under "run as". It is a way to use relative paths and still get reasonable behavior inside eclipse. – Tim Perry Jul 22 '10 at 17:17
  • True, there are will always be workarounds and ducktapes, but you really don't want to have your application to be permanently dependent on that when there are much better ways. – BalusC Jul 22 '10 at 17:35
1

Try giving an absolute path to the filename.

Also, post the code so that we can see what exactly you're trying.

chimeracoder
  • 20,648
  • 21
  • 60
  • 60
  • It can't get pass this line: Scanner sc1 = new Scanner(new File(args[0])); and i passed my text file as the the first arg – Victor Jul 22 '10 at 15:16
  • Combining lines can help shorten code and possibly improve performance (speed), but when debugging, it helps to split things up (ie, not embed constructors within constructors). Create a File object, see if this is the place where the program trips up. If not, then pass the File object to Scanner (in a separate line) and see what type of error gets thrown. – chimeracoder Jul 22 '10 at 15:28
1

When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.

you can find the current working directory of your process using

String workindDir = new File(".").getAbsoultePath()

Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).

Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
0

If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.

Check out this question for more detail.

Community
  • 1
  • 1
perimosocordiae
  • 17,287
  • 14
  • 60
  • 76
0

If you put the file and the class working with it under same package can you use this:

Class A { 


    void readFile (String fileName)  {
    Url tmp = A.class.getResource (fileName); 
    // Or Url tmp = this.getClass().getResource (fileName);

    File tmpFile = File (tmp);

    if (tmpFile.exists()) 
        System.out.print("I found the file.")

    }

} 

It will help if you read about classloaders.

bluish
  • 26,356
  • 27
  • 122
  • 180
Govan
  • 2,079
  • 4
  • 31
  • 53
0

The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.

Truong Ha
  • 10,468
  • 11
  • 40
  • 45
0

say I have a text file input.txt which is located on the desktop and input.txt has the following content

i came
i saw 
i left

and below is the java code for reading that text file

public class ReadInputFromTextFile {
    public static void main(String[] args) throws Exception
    {
        File file = new File(
                "/Users/viveksingh/desktop/input.txt");
        BufferedReader br
                = new BufferedReader(new FileReader(file));
        String st;
        while ((st = br.readLine()) != null)
            System.out.println(st);
    }
}

output on the console:

i came
i saw 
i left
Vivek Singh
  • 959
  • 7
  • 10