views:

123

answers:

4

Let's say I have my main class in C:\Users\Justian\Documents.

How can I get my program to show that it's in C:\Users\Justian\Documents.

Hard-Coding is not an option- it needs to be adaptable if it's moved to another location.

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

Many thanks,

Justian

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

@BalusC

Why is:

public static String getCleanPath() {
    ClassLoader classLoader = ExcelFile.class.getClassLoader();
    File classpathRoot = new File(classLoader.getResource("").getPath());

    return classpathRoot.getPath();
}

Better than:

public static String getCleanPath() {
    URL location = ExcelFile.class.getProtectionDomain().getCodeSource()
            .getLocation();
    String path = location.getFile();

    return new File(path).getParent();
}
A: 

take a look at this article.

Matthew J Morrison
+2  A: 

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Michael Borgwardt
I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.
Justian Meyer
Maybe I'm missing something but it seems like an absolute path would work. You said you can't hardcode it, but how are you going to know what folder to look in to begin with?
Chris Thompson
Well the issue is that I want to bring it over to other computers, not just my own. I don't see how hardcoding the path would work. "Assume that my jar and folder will always have a similar relationship (i.e. in the same directory). If this was true, I could get the directory of the jar, then modify it to find the folder." The only way I could hardcode it would be if I didn't have to include the full path from the hard drive to the file. Maybe I can go just 3 folders back (i.e "Documents\Project\Dump\[file/folder]")
Justian Meyer
I would say what you want to do is get a handle to the directory the jar file resides in. Would that accomplish your requirements?
Chris Thompson
Yes. Exactly :)
Justian Meyer
+2  A: 

Use CodeSource#getLocation(). This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument.

BalusC
+1. There are several conditions to make this work; the most important is that your "main class" is loaded from the file system. In Java, it's not terribly unusual for this assumption to be false. But, if you are sure that you are loading your class from a JAR on the file system, this is *the* method that works.
erickson
It all depends, really. I'm **trying** to get my JAR to compile, but that's a separate issue at the moment. If you think you can help with that, check out: http://stackoverflow.com/questions/3152240/jar-cant-find-main-method-connected-to-main-class-but-cant-access-method . I'm sure that posting this is an infraction of some kind, but it is related to this issue. If I can get that fixed, this will for sure be my answer.
Justian Meyer
Why would I need to hardcode that? I've done similar things before. Assume that my jar and folder will always have a similar relationship (i.e. in the same directory). If this was true, I could get the directory of the jar, then modify it to find the folder.
Justian Meyer
If it's in the same folder as the JAR file, then it's just already in the classpath. The word "hardcoding" is a bit exaggerated, I actually meant "knowing their path relative to the JAR file".
BalusC
It can't seem to find ClassLoader.
Justian Meyer
Depending on the context, just get it by `getClass().getClassLoader()` or `Foo.class.getClassLoader()` or (preferably) `Thread.currentThread().getContextClassLoader()`. There are also shorthand `getResource()` methods in `Class`. Read the javadocs ;)
BalusC
-Chose as best answer- Quick question before you go. Best way to remove CC.jar from the path name? Recursion cutting off the segments before each "/", getting the name, then cutting the string down where it finds "CC.jar" or whatever I get from the recursion? Maybe a little overly confusing =/.
Justian Meyer
`File#getParent()`. So, you're going for the non-classpath approach? A bit clumsy since the JAR's root path is already covered by the classpath...
BalusC
Why would. `public static String getCleanPath() { URL location = ExcelFile.class.getProtectionDomain().getCodeSource() .getLocation(); String path = location.getFile(); return new File(path).getParent(); }` Not work?
Justian Meyer
Moving that to the top for easy-reading.
Justian Meyer
"It does not work" is too ambiguous. Be more precise. Also, why do you keep preferring this above `new File(classLoader.getResource("").getPath())`
BalusC
Look at edit to question above.
Justian Meyer
+2  A: 

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

fuzzy lollipop
I'll test this out when I can. I'm really preoccupied with that .jar issue :P
Justian Meyer
did you visit the link in my answer to that .jar issue, where I show how to build the .jar file with ANT?
fuzzy lollipop