?
Solved

Relative File Path

Posted on 2003-10-26
4
Medium Priority
?
333 Views
Last Modified: 2010-03-31
I have a java app that writes a file inside a tree pf directories. The program works fine in Windows, but under Linux I cannot use a realtive file path, it only works with an absolute.

The directory structure is like: DAT/dir1/dir2/dir3

How do I either get the directory path that my program was run from (ie so I can use that path + DAT/dir1/dir2) or write to one of those dirs without providing an absolute path?

Thanks.
0
Comment
Question by:knight1093
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 2

Expert Comment

by:f_98
ID: 9624655
relative directories should work fine on linux; you could try adding a "./" and see if it works or

this will give you the current directory:

   public String getCurrentDir()
   {
      File dir1 = new File (".");
      String strCurrentDir = "";
      try  {
        strCurrentDir = dir1.getCanonicalPath();
      }
      catch(Exception e)  {
         e.printStackTrace();
      }
      return strCurrentDir;
   }
0
 

Author Comment

by:knight1093
ID: 9624692
f_98, that is only giving me /home/user instead of /home/user/prog/dir, which is where my program is being run from. I also tried ./ and ../, but it didn't work.
0
 
LVL 2

Accepted Solution

by:
f_98 earned 200 total points
ID: 9624733
hmm, the closest thing i could think of right now is trying
getClass().getResource("Myclass.class");
which returns the URL of that class.

from somewhere else:

String resource = locate();
String mylocation = resource.trim().substring(resource.indexOf('C'),resource.lastIndexOf('/')).replace('/','\\') + "\\";

public String locate() {
        final URL loc = getClass().getResource( "YourClass.class" );
        try {
            String pathString;
            pathString = URLDecoder.decode( loc.getPath(), "UTF-8" );
            //System.out.println( "pathString: "+pathString );
            if( pathString.startsWith( "file:" ) )
            {
                pathString = pathString.substring( "file:".length() );
            }
            //System.out.println( "pathString: "+pathString );
            final int jarIndex = pathString.indexOf( ".jar!" );
            if( jarIndex > -1 )
            {
                pathString = pathString.substring( 0, jarIndex + ".jar".length() );
            }
            //System.out.println( "pathString: "+pathString );
            final String sep = System.getProperty( "file.separator" );
            final int pathSepIndex = pathString.lastIndexOf( sep );
            if( pathSepIndex > -1 )
            {
                pathString = pathString.substring( 0, pathSepIndex + sep.length() );
            }
            //System.out.println( "Jar file located at: " + pathString );
            return pathString;
        } catch( UnsupportedEncodingException uee ) {
        // this should never happen for UTF-8!!!
        }
        return "";
    }
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9625544
System.getProperty("user.dir") will give you the current working directory.

I'm not sure you need this.  The following code handles a file in the directory from which the class is executed:

import java.io.*;

public class FilePathTest
{
    public static void main(String[] args)
    {
        File myFile = new File("Hello.tmp");
        System.out.println("Path = " + System.getProperty("user.dir"));
        try
        {
            System.out.println(myFile.getCanonicalPath());
        }
        catch (IOException ioe)
        {
            System.err.println("ioe: " + ioe.toString());
        }
    }
}

ie.  Executed from /home/jim/expertsexchange/FilePathTest, I get:

Path = /home/jim/expertsexchange/FilePathTest
/home/jim/expertsexchange/FilePathTest/Hello.tmp

If I go to my home directory and type:

java -cp expertsexchange/FilePathTest FilePathTest, I get:

Path = /home/jim
/home/jim/Hello.tmp

One other point.  If your code is designed to be used on multiple platforms, don't forget to use File.pathSeparator instead of "/" or "\" ;-)

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month15 days, 17 hours left to enroll

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question