Allan said:
Is it possible to get the directory of the file that contains my main()? I
have a few data files in a subdirectory within this directory and I want to
access them like this:
public static final String myDataSubdir = "Data\\";
public static final String myDataFile = "Data1.txt";
// access the file using the below as my String
// myMainDirectory + myDataSubdir + myDataFile
If you want to read the file, the easiest way is to use a resource:
URL resource = MyMainClass.class.getResource("data/data1.txt");
// Read the URL using openStream
If you need full read/write access, then things get more complicated.
You should first realize that Java is designed to load classes from
anywhere; including read-only resources like HTTP, hard-to-write
locations like a JAR file (which requires rewriting the entire archive
to make general-case modifications), or potentially even auto-generated
code from an intelligent classloader that isn't stored anywhere at all.
Now if you're absolutely certain that you will always be running your
code from class files stored directly in the filesystem (generally an
unnecessarily messy arrangement), then the following code will probably
work for you:
CodeSource source = MyMainClass.class
.getProtectionDomain().getCodeSource();
if (source == null) return null;
File baseDir;
try
{
URI sourceURI = new URI(source.getLocation().toString());
baseDir = new File(sourceURI);
}
catch (URISyntaxException e)
{
return null;
}
catch (IllegalArgumentException e)
{
return null;
}
if (!baseDir.isDirectory()) return null;
String[] classComponents = MyMainClass.class
.getName().split("\\.");
for (int i = 0; i < classComponents.length - 1; i++)
{
baseDir = new File(baseDir, classComponents
);
}
File dataDir = new File(baseDir, "data");
File dataFile = new File(dataDir, "data1.txt");
if (!dataFile.isFile()) return null;
else return dataFile;
HTH,
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation