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
Solved

Relative File Path

Posted on 2003-10-26
4
328 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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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 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:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 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