views:

249

answers:

4

How do you scan a file with java that isn't in the directory the java file is in?

For example: The java file is located at "C:\Files\JavaFiles\test.java" However, the file I want to scan is located at "C:\Data\DataPacket99\data.txt"

Note: I've already tried putting another java file in the "C:\Data" directory and using the test.java file as a class, but it doesn't work. It still tries to scan from the "C:\Files\JavaFiles" Directory.

+1  A: 

By using an absolute path instead of a relative.

File file = new File("C:\\Data\\DataPacket99\\data.txt");

Then you can write code that accesses that file object, using a InputStream or similar.

willcodejavaforfood
I think you should escape the slashes; c:\\data\\DataPacket99\\data.txt
extraneon
You definitely don't want to be using backslashes as pathname separators in a Java String!
Carl Smotricz
Escape or, better yet, use forward slashes.
Carl Smotricz
Unless it's always expected to be in the same directory, a file chooser would probably be a better approach to use than hard coding an absolute path. Just use a file chooser and user the resulting handle for the file to open.
illvm
Thanks willcodejavaforfood!
DDP
extraneon - I've updated my post, cheers mate
willcodejavaforfood
+2  A: 

You need to use absolute paths in java.io stuff. Thus not new File("data.txt"), but new File("C:/Data/DataPacket99/data.txt"). Otherwise it will be relative to the current working directory which may not per-se be the same in all environments or the one you'd expect.

BalusC
Thanks a lot BalusC! :D
DDP
+1  A: 

I would try this:

File file = new File("../../Data/DataPacket99/data.txt");
Drewen
+1  A: 

You should be using an absolute path instead of a relative path.

You could use File file = new File("C:/Data/DataPacket99/data.txt"); but it might make your life easier in the future to use a file chooser dialog if at any point the user will have to enter a file path.

_wdh
Oh dang, awesome (for the file chooser dialog). Thanks _wdh!
DDP