Solved

Relative File Path

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 84
groupSum6 challenge 6 86
groupSumClump challenge 9 115
runtime exception 2 27
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

776 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