Hi again!! my program involves accessing a text file.. my problem is that, i have to type the absolute path of that file on for the program to work... Then I put all my files in a directory and zipped my java source files, and packages, and classes, and text file... Now when unzipped run my program on another computer I still have to change the path of that file in my java file and then recompile it again... i.e. (in the 1st computer my java file contained: String textfile = "C:\\Project1\\subdirect\\textfile.txt"; Now when i unzipped it in another computer in a different directory, obviously the java file won't run unless i edit it and change the line... and then recompile again... What should I do so that I'll just specify only the filename of my text file.. and so that i won't recompile again...
Well the first thing to do is to not use absolute paths! Seriously. You've already seen why. The java.io.File class has some things that will help. This horribly misnamed construct has all sorts of ways to work with filenames and to manipulate the files which they represent. One of the most useful is the directory+filename constructor. Since a directory is also a File object, you can do things like:
You can get the absolute path in full by requesting "myfile.getAbsolutePath()" - which I use for things like error reporting. You can ALSO use unix-style path syntax, even under Windows. I prefer it because it's more universal and because you don't get burned by the "backslash=exscape character" problem. Another way to ease locating a file are to put the path in a resource file (which can then be edited with a simple notepad program). Note also that if you store the path in an environment variable, you can pass it in as a parameter like so:
This means you can have a standard BAT file and standard program and just set the machine's environment. That's also good if, for example, the primary copy of the file's on a network driver and the network goes down and you have to use a local copy.
The secret of how to be miserable is to constantly expect things are going to happen the way that they are "supposed" to happen.
You can have faith, which carries the understanding that you may be disappointed. Then there's being a willfully-blind idiot, which virtually guarantees it.
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
a bit of art, as a gift, that will fit in a stocking