Solved

Relative File Path

Posted on 2003-10-26
4
319 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
  • 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 50 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
create a gui in perl 3 70
java 8 lambda expresssions exception handling 3 74
Basic Java Case or If-Else statement... 3 43
java stored proc example 9 20
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

911 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now