Get absolute path to File

2.3k views Asked by At

So I'm trying to use BufferedImages necause their eaier for and it seems loading them is a bit more finiky. I think you need the absolute path to load them and I have tried just doing src/Package.image.png but when I export to runnable jar it doesn't work. This code works inside eclipse but for some reason it doesn't work when I export it as a .jar .

package MainGame;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

 public class GraphicsPath {





public static String getGraphicsPath(){


    String path = null;

    PrintWriter writer = null;
    try {
        writer = new PrintWriter("text.txt");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    path = GraphicsPath.class.getProtectionDomain().getCodeSource().getLocation().getPath();  


    System.out.println(path);

    writer.println("orignal path    " + path);

    //FOR LINUX
    String[] splited = path.split("/");


    //FOR WINDOWS
    //String[] splited = path.split("\");
    writer.println(path);


    path = path.replace("%20", " ");

    path += "MainGame/";

    writer.println(path);
    writer.close();

    System.out.println(path);
    return path;

}

}

Here is the contents of text.txt when its exported to the jar

orignal path    ./
./
./MainGame/

Here is the contents of text.txt while still in the java project

orignal path    /home/mini/workspace/Pokemon%20Game/bin/
/home/mini/workspace/Pokemon%20Game/bin/
/home/mini/workspace/Pokemon Game/bin/MainGame/
3

There are 3 answers

0
Evilsanta On BEST ANSWER

If I understand you correctly, you have a package.image.png file that you need to read, it is inside the .jar file.

I have had this problem before, and I think you cannot use path to locate this file. In one of my projects I actually used a URL to specify the location of the file. I'll give you an example of what I did

so In my jar file, there is a images folder. say i have /images/x.png

I do this

URL u = this.getClass().getResource( "/images/x.png" );
a=ImageIcon(u);

I used this to create imageIcon, but I think you can check how to read a file with URL.

EDIT: I just tried this to read a file, it works.

URL test =Class.class.getResource( "/docs/test.txt" );
BufferedReader in = new BufferedReader(new InputStreamReader(test.openStream()));

So you can wrap the InputStreamReader with other stuff to get the image

0
AudioBubble On

You can pass paths in a lot of ways. Please check some below, maybe one of them can work for you:

Directory structure

package test;

import java.io.File;
import java.io.IOException;

public class FilePaths {

    public static void main(String[] args) throws IOException {

        String[] fileArray = { 
                "C:\\projects\\workspace\\testing\\f1\\f2\\f3\\file5.txt", 
                "folder/file3.txt",
                "../testing/file1.txt", 
                "../testing", 
                "f1/f2"
        };

        for (String f : fileArray) {
            displayInfo(f);
        }

    }

    public static void displayInfo(String f) throws IOException {
        File file = new File(f);
        System.out.println("========================================");
        System.out.println("          name:" + file.getName());
        System.out.println("  is directory:" + file.isDirectory());
        System.out.println("        exists:" + file.exists());
        System.out.println("          path:" + file.getPath());
        System.out.println(" absolute file:" + file.getAbsoluteFile());
        System.out.println(" absolute path:" + file.getAbsolutePath());
        System.out.println("canonical file:" + file.getCanonicalFile());
        System.out.println("canonical path:" + file.getCanonicalPath());
    }

}

More about file paths here.

0
David Ehrmann On

Making it a bit too easy, if you put your image resources in the same directory as GraphicsPath (both on the classpath), you can do

BufferedImage image;
try (InputStream in = GraphicsPath.class.getResourceAsStream('my-image.png')) {
    if (in != null) {
        image = ImageIO.read(in );
    }
}

This is what you want to do. If you use an EAR, a WAR, JNLP, java -jar, or, my apologies, applets, playing with paths might not even work. Bundling resources beside a class you know exists means you'll have easy access to those resources.

Now, in your case, it's clunky because they won't be copied to the bin directory for you, so you might need to edit the classpath you use for development.