Solved

Relative File Path

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
hash value 2 38
copyEndy  challenge 15 58
PDFBox - convert image to PDF, PDF resolution 3 70
create a gui in perl 3 46
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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 “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

760 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

19 Experts available now in Live!

Get 1:1 Help Now