Finding the directory path in java

I need to check if a file exists or not before an action is taken. I used File class to get the handle of a file and and then used exist() function to check if it is there. But this function needs to full path to that file. I need to find a directory path at runtime as the application is deployed in different environment and wouldn't know the directory path in each environment. Could somebody help me on this. Thanks,

fBut this function
needs to full path to that file. I need to find a
directory path at runtime as the application is
deployed in different environment and wouldn't know
the directory path in each environment. Well, that can only you know where this file is on the different platforms. So maybee you can provide it as a user-input, a parameter to the program or be set in a settings-file which the program reads.
If you want the full path to the current directory where the java program runs, this works:
File f=...;
String absPath=f.getAbsolutePath();
File absPathFile=new File(absPath);Gil

Similar Messages

  • Finding the directory path

    i'm not sure what is the best way to determin th epath (location) of a directory or a file.
    example (IDE enviroment)
    [app]
       |----[config]
       |           |---- log4j.properties
       |           |---- application.properties
       |
       |----[classes]  
       |           |---- MyApp.classesexample: deployment
    [app]
       |----[config]
       |           |---- log4j.properties
       |           |---- application.properties
       |
       |----myapp.jar   (excutable jar file)
       |----START.BAT file
       |----STOP.BAT fileSTART.BAT
    java -jar myapp.jar
    public class MyApp{
        public MyApp(){
            String path = MyApp.class.getResource("/").getPath();
            System.out.println(path.replaceAll("%20", " "));
    }in the IDE, i have noo problem with the String path = MyApp.getResource();
    i think this is because the working directory is [classes]
    if i run from the "deployment using a jar file...i would get NULLPointerException
    the getResource would return null
    this is because the working directory is [app]
    Is there a way to get the location of the MyApp class (where the working directory should not matter)?

    i think i see the problem:
    the MyApp is in a jar file...and MyApp is not in a package;
    therefore getResource("/") // look for the directory that MyApp is in
    iwould return null...since it's (technically) not in any directory - no package specified
    am i correct?

  • How do you set/find the directory path for /i/

    Searching the forum, I found one note that indicated this was set in MARVEL.CONF (since I'm running 2.0, presumably DADS.CONF). However, looking at the DADS file for my install, I don't see anything resembling a directory mapping. What would the syntax be for this?

    In a default installation, you are supposed to add the mapping to httpd.conf
    But it could be in any file Apache includes.
    Seach for a line like
    Alias /i/     "/opt/oracle/product/10.1.0/Apache/Apache/images/"

  • Finding the exact path of a file using a Java program

    Can anyone tell me how to find the exact path of a file which is saved in a directory other than the one in which the main file is saved? I know there is a class called File which has many methods like isAbsolutePath() and isPath() but they return the path in which the main class is located

    actually i m trying to write a program which will
    take a name of a file or a directory from the console
    and it should give the entire path of that file or
    directory and this file need not be stored in the
    path of the main class.....It can be stored in any
    drives of my PC....Ok, then the console input needs to be an absolute path or a path relative to some given directory (usually the one from which the application is started). Java cannot magically guess absolute paths if you just provide a file name. E.g. if I'd use your program and would provide as input "build.xml", how should the program know which file by that name I mean (there are lots of build.xml files in different locations on my machine)?

  • Find Cache Directory Path

    Is it possible to find the webstart cache directory path using java webstart API.
    Thanks

    - Put the HTML in a jar archive
    - Reference the jar in the JNLP
    - Access it using getResource() and..
    - Display it in a JEditorPane
    (fine for simple and valid HTML)
    Alternately, if you intend to show the page in a
    browser, and want to have a sandboxed applet,
    you might..
    - ask the user where they want to save the HTML
    (via the FileSaveService)
    - save it there.
    - store the full path of the downloaded HTML using
    the PersistenceService*
    - load it, when required, using the FileOpenService.
    It might pay to explain to the end user that this
    file is used regularly and it makes sense to tick
    the 'always allow' box for 'ease of later use'.
    * Only necessary if you want to cache the HTML
    between runs, obviously.

  • How to find the absolute path of file  which store in KM foler ?

    Hello everyone:
         We want to develop an ABAP program which can write files into KM folder directly.
         So I need to find the absolute path of file which store in KM folder first, then we can consider the develop solution.
         Is this issue possbile that an ABAP  program write files into KM folder  directly ?
         Is there anybody had done this job ?
    Best Regards,
    Jianguo Chen

    Hi,
    http://forum.java.sun.com/thread.jsp?forum=34&thread=36
    612The methods in the above topic seem to be available when use a DOM parser..

  • Finding the shortest path

    Hey guys,
    Im working on a solution to this problem below is a program to allow a user to draw straight line paths. What i'd like to do is allow the user to select two points on the path he has drawn and find the shortest path among all the interesecting lines.....im going crazy thinking of a solution for this.....im thinking bout steeping down a notch and just try to find just any path first.
    Will really appreciate any help.
    Thnx in advance,
    Vikhyat
    import java.applet.*;*
    *import java.awt.*;
    import java.awt.event.*;*
    *import javax.swing.*;
    import java.awt.geom.*;
    public class Lab11 extends Applet implements MouseListener, MouseMotionListener {
    int x0, y0, x1, y1;
    int mouseRelease=0;
    GeneralPath path = new GeneralPath();
    public Lab11()
    addMouseListener(this);
    addMouseMotionListener(this);
    public void mouseDragged(MouseEvent e)
    x1 = e.getX();
    y1 = e.getY();
    repaint();
    public void mouseMoved(MouseEvent e) { }
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited (MouseEvent e) { }
    public void mousePressed(MouseEvent e) {
    x0 = e.getX();
    y0 = e.getY();
    System.out.println("Mouse pressed at: (" +
    x0 + ", " + y0 + ")" );
    public void mouseReleased(MouseEvent e) {
    x1 = e.getX();
    y1 = e.getY();
    System.out.println("Mouse released at: (" +
    x1 + ", " + y1 + ")" );
    mouseRelease = 1;
    this.repaint();
    public void paint(Graphics g)
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    //just for show not concerned with saving paths
    if(mouseRelease==1)
    path.moveTo(x0,y0);
    path.lineTo(x1,y1);
    mouseRelease = 0;
    g2.setPaint(Color.RED);
    g2.draw(path);
    g.setColor(Color.BLACK);
    g.drawLine(x0, y0, x1, y1);
    public static void main(String[] argv)
    JFrame f = new JFrame("Test");
    f.getContentPane().add(new Lab11());
    f.setSize(600,600);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Pictorially this is what im trying to do:
    User draws a path like so and selects two points as shown in blue
    [http://i48.photobucket.com/albums/f236/theforrestgump/select.jpg]
    The program should then proceed to highlighting the shortest path
    [http://i48.photobucket.com/albums/f236/theforrestgump/sp.jpg]
    Edited by: cannonball on Apr 1, 2008 7:58 PM

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ShortPath extends JPanel {
        Path2D.Double path;
        Path2D.Double shortPath = new Path2D.Double();
        Point p1 = new Point();
        Point p2 = new Point();
        final double PROXIMITY = 5.0;
        public ShortPath() {
            path = new Path2D.Double();
            path.moveTo(145,80);
            path.lineTo(125,170);
            path.lineTo(190,200);
            path.lineTo(240,340);
            path.lineTo(285,220);
            path.lineTo(145,80);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            g2.draw(path);
            g2.setPaint(Color.green);
            g2.setStroke(new BasicStroke(2f));
            g2.draw(shortPath);
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(p1.x-2, p1.y-2, 4, 4));
            g2.setPaint(Color.orange);
            g2.fill(new Ellipse2D.Double(p2.x-2, p2.y-2, 4, 4));
        private void findShortPath() {
            if(!isPointOnLine(p1) || !isPointOnLine(p2)) {
                System.out.println("a point is not on the path");
                return;
            double d1 = getDistanceToPoint(p1);
            double d2 = getDistanceToPoint(p2);
            double pathLength = getDistanceToPoint(new Point());
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end   = new Point2D.Double();
            if((d1 < d2 && d2 - d1 < pathLength - d2 + d1) ||
               (d1 > d2 && d1 - d2 > pathLength - d1 + d2)) {
                start.setLocation(p1);
                end.setLocation(p2);
            } else {
                start.setLocation(p2);
                end.setLocation(p1);
            generatePath(start, end);
        //                        145,80
        // leg distance = 92.2    125,170
        // leg distance = 71.6    190,200   163.8
        // leg distance = 148.7   240,340   312.5
        // leg distance = 128.2   285,220   440.7
        // leg distance = 198.0   145,80    638.7
        private double getDistanceToPoint(Point p) {
            PathIterator pit = path.getPathIterator(null);
            double[] coords = new double[2];
            double distance = 0;
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                        start.setLocation(coords[0], coords[1]);
                        pit.next();
                        continue;
                    case PathIterator.SEG_LINETO:
                        end.setLocation(coords[0], coords[1]);
                line.setLine(start, end);
                boolean onLine = line.ptSegDist(p) < PROXIMITY;
                if(onLine) {  // point is on this line
                    distance += start.distance(p);
                    break;
                } else {
                    distance += start.distance(end);
                start.setLocation(end);
                pit.next();
            return distance;
        private void generatePath(Point2D.Double first, Point2D.Double second) {
            Point2D.Double p = new Point2D.Double(first.x, first.y);
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            boolean pathStarted = false;
            for(int j = 0; j < 2; j++) {
                PathIterator pit = path.getPathIterator(null);
                double[] coords = new double[2];
                while(!pit.isDone()) {
                    int type = pit.currentSegment(coords);
                    switch(type) {
                        case PathIterator.SEG_MOVETO:
                            start.setLocation(coords[0], coords[1]);
                            pit.next();
                            continue;
                        case PathIterator.SEG_LINETO:
                            end.setLocation(coords[0], coords[1]);
                            line.setLine(start, end);
                            boolean onLine = line.ptSegDist(p) < PROXIMITY;
                            if(onLine) {            // found point on line
                                Point2D.Double linePt = getClosestPoint(line, p);
                                Line2D.Double segment;
                                if(!pathStarted) {  // found first point
                                                    // both points on line
                                    if(line.ptSegDist(second) < PROXIMITY) {
                                        Point2D.Double secPt =
                                            getClosestPoint(line, second);
                                        segment = new Line2D.Double(linePt, secPt);
                                        shortPath.append(segment, false);
                                        return;
                                    } else {        // first point only
                                        segment = new Line2D.Double(linePt, end);
                                        shortPath.append(segment, false);
                                        p.setLocation(second);
                                        pathStarted = true;
                                } else {            // found second point
                                    segment = new Line2D.Double(start, linePt);
                                    shortPath.append(segment, false);
                                    return;
                            } else if(pathStarted) {
                                                    // add intermediate lines
                                Line2D.Double nextLine =
                                    new Line2D.Double(start, end);
                                shortPath.append(nextLine, false);
                    start.setLocation(end);
                    pit.next();
        private Point2D.Double getClosestPoint(Line2D.Double line,
                                               Point2D.Double p) {
            double minDist = Double.MAX_VALUE;
            Point2D.Double closePt = new Point2D.Double();
            double dy = line.getY2() - line.getY1();
            double dx = line.getX2() - line.getX1();
            double theta = Math.atan2(dy, dx);
            double length = line.getP2().distance(line.getP1());
            int limit = (int)(length+.05);
            for(int j = 0; j < limit; j++) {
                double x = line.getX1() + j*Math.cos(theta);
                double y = line.getY1() + j*Math.sin(theta);
                double distance = p.distance(x, y);
                if(distance < minDist) {
                    minDist = distance;
                    closePt.setLocation(x, y);
            return closePt;
        private boolean isPointOnLine(Point p) {
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            PathIterator pit = path.getPathIterator(null);
            double[] coords = new double[2];
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                        start.setLocation(coords[0], coords[1]);
                        pit.next();
                        continue;
                    case PathIterator.SEG_LINETO:
                        end.setLocation(coords[0], coords[1]);
                        line.setLine(start, end);
                        if(line.ptSegDist(p) < PROXIMITY) {
                            return true;
                start.setLocation(end);
                pit.next();
            return false;
        public static void main(String[] args) {
            ShortPath test = new ShortPath();
            test.addMouseListener(test.ml);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private MouseListener ml = new MouseAdapter() {
            boolean oneSet = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(oneSet) {
                    p2 = p;
                    findShortPath();
                } else {
                    p1 = p;
                    shortPath.reset();
                oneSet = !oneSet;
                repaint();
    }

  • Find the installation Path of the current running VM on Windows

    Hello,
    I have a java class started by webstart.
    In this class I would like to find the absolute path of the current running vm? This is important to me because I need to start an exe file (using ProcessBuilder) and hand it the path of the java VM,
    For example I could try something like this:
    private static File findJDK() throws Exception {
    String s = System.getProperty("java.home");
    File myJRE = new File(s);
    if (new File(myJRE, "bin/javac.exe").isFile()) {
    return myJRE;
    File parent = myJRE.getParentFile();
    if (new File(parent, "bin/javac.exe").isFile()) {
    return parent;
    for (String pathel : System.getenv("PATH").split(File.pathSeparator)) {
    File bindir = new File(pathel);
    if (new File(bindir, "javac.exe").isFile()) {
    return bindir.getParentFile();
    return myJRE;
    But I would like the above code to be more fool proof!
    For example the "java.home" could be wrongly set.
    Since java is allready running I would have hopped that I could query the Runtime. But there seems to be no method providing the running java VM path?
    I also tried looking at the jnlp services API but no luck.
    I would be also interested find the lastest java VM on the client Windows machine....
    Many greetings
    john

    http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties()
    bye
    TPD

  • Want to output only the directory path in the jTextField

    Currently, I am getting the directory path, but need to select a file inside it, then only the directory path gets selected in the jTextField1. Please tell me how do I get the directory path in jTextField1 by selecting only the directories in jButton1.
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
         JFileChooser dirchoose=new JFileChooser();
         dirchoose.setCurrentDirectory(curfile);
         String directory=dirchoose.getCurrentDirectory().toString();
         int stat=dirchoose.showOpenDialog(this);
         if(stat==JFileChooser.APPROVE_OPTION)
              curfile=dirchoose.getCurrentDirectory();
              jTextField1.setText(dirchoose.getCurrentDirectory().toString());
              String jTextField1Text=jTextField1.getText();
    File curfile=new File("C:\\");

    Please ignore this topic. I am new here and was bit confused with the forum.

  • How to find the tomcat path from registry?

    Hi,
    How can I find the tomcat path from registry?
    please tell me.
    Thanks
    Gaurav Agrawal

    gauravjlj wrote:
    listen,
    I'm about to create a exe which will do these things.....
    1. first install java
    2. install tomcat
    3. install mysql
    4. deploy my web application with out use of tomcat manager
    first three steps I have done with the help of installer maker. let assume that my tomcat has been installed. but now please tell me how can I deploy my web application.
    that's why I need the tomcat path.
    please tell me.Well, if you've just installed Tomcat you do know where it is so what's the problem? Why not, in fact, include your application in the tomcat directories as you install them? That's all there is to installing tomcat, installing the directories, setting %JAVA_HOME% and (possibly) running the service.bat file.

  • Installed new update iTunes Saturday - My file directory could not be found, so reset the directory path, 'it' asked me if I would like 'it' to re organise filing, I selected yes - Many tunes have been duplicated, some have disappeared. Any help?

    Hi,
    Installed a new update iTunes Saturday - My file directory could not be found, so I reset the directory path, and 'it' asked me if I would like 'it' to re organise my filing, foolishly (as a beginner, without checking)  I selected yes - Many tunes have been duplicated, some have disappeared? Trawled through lots of misleading help files, mailed friends, tried many back routes into Apple web sites and they all wasted my time. Can anyone help?
    I have discovered since then, that this resorce has been down over the weekend, which probably explains why I have had so many contradictory responses, so apologies if you all know what the prolem is.
    My question is, my TIME MACHINE (which has not been used yet) was tried but looked nothing like that of the U Tube demo, so I am assuming that it needs setting up, however, it has been saving, I just do not know how to recover the data. Can anyone help?
    Regads,
    Cyfrommayo

    (If you have a Time Machine backup, go to your User folder/Music/iTunes and select iTunes. Enter Time Machine and go to a backup of iTunes before the above happened. Then select 'Restore' on the bottom right.)
    Eric,
    Many thanks for your help.
    Apologies for not being as skilled as you. I am unable to see what you are saying, can I ask, should I be in TIME MACHINE when I go to User folder/Music?iTunes or iTunes or Finder?
    Cyfrommayo

  • Ftp connection: "Can not find the catalog/path"

    I have had a Webserver operating on my old IBook.
    I had it opened through my firewall, and everything worked.
    Now I try to connect to the same iBook, but with an IP-adress that comes from turning on
    Internet sharing on the Ethernet port of my iMac. I try to connect in iWeb, ftp server test.
    But the iMac I do things on, cannot find the catalog, it says. (At least the ftp login seems to work.)
    I have things in the path /Library/Webserver/Documents, and started my 3rd
    home page in the subdirectory iMe, which catalog I created inside the Documents folder.
    Thankful for all tips!
    Best Regards,
    /Peter K, Sweden

    As per usual, do not compond problems, mix them and then cry for help. And iWeb is not involved, yet.
    Start at the beginning.
    Set up your network and make it work. Period.
    On the remote computer where you want to have access, and publish your website, enable Remote login.
    Then test it and find out where you end up.
    There you create a folder where you want to publish your pages.
    Put a sampe html file in that folder.
    In the /Library/Webserver/Documents folder on that remote computer you create a symlink to that folder.
    Open your browser and type the URL to the file.
    TEST TEST TEST TEST TEST TEST TEST
    UNTIL IT WORKS.
    If you do not understand it, search the interwebs or find a forum that deals with it.
    Then, when it works, and only then, you may open iWeb.
    To publish to that remote folder you created earlier, choose this setting :
    The directory path is determined earlier when you tested the connection.
    You can also use filesharing.
    Enable it on the remote computer and then mount the remote disk on your desktop.
    Choose publish to folder in iWeb.
    iWeb doesn't care.

  • Size with the directory path

    Hello All,
    I have a sricpt called "findlarge" to find large file existed in the FS.
    When I have run this script give me only the size as below:
    #./findlarge /u01/test
    : 243M
    : 230M
    : 203M
    I want size with the directory path.
    Am I missing some thing?
    Some thing like below:
    /:243 u01/test/node1
    SCRIPT:
    #!/bin/bash
    # if nothing is passed to the script, show usage and exit
    [[ -n "$1" ]] || { echo "Usage: findlarge [PATHNAME]"; exit 0 ; }
    # simple using find, $1 is the first variable passed to the script
    find $1 -type f -size +100000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
    D

    Das N wrote:
    Hello All,
    I have a sricpt called "findlarge" to find large file existed in the FS.
    When I have run this script give me only the size as below:
    #./findlarge /u01/test
    : 243M
    : 230M
    : 203M
    I want size with the directory path.
    Am I missing some thing?
    Some thing like below:
    /:243 u01/test/node1
    SCRIPT:
    #!/bin/bash
    # if nothing is passed to the script, show usage and exit
    [[ -n "$1" ]] || { echo "Usage: findlarge [PATHNAME]"; exit 0 ; }
    # simple using find, $1 is the first variable passed to the script
    find $1 -type f -size +100000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
    DThis is a bit of a brute force method ....
    Try changing
    {code}
    find $1 -type f -size +100000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
    {code}
    to
    {code}
    find $1 -type f -size +100000k -exec ls -lh {} \; | awk '{ print $8 ": " $5 }'
    {code}
    If that fails try $7, $6 ....
    Rgds - bigdelboy

  • How to find the menu path ?

    Hi all,
    I have one doubt how do we find out the correct menupath if we know the t-code ?
    for example, SE11 -DDIC
    we can also obtain the same DDIC screen via menupath from SAP main screen.
    if I know only t-code.how can i find out the menupath ?
    thnks and rgds,
    raghul

    Hi Raghul,
      You can go to the transaction search_sap_menu
    for finding the menu path.
    check this link:
    http://www.sap-basis-abap.com/sapgeneral/system-path-and-transaction-code-mapping.htm
    Hope this helps you.
    Regards,
    Chandra Sekhar

  • Need Help in finding the Menu Path's for the below topics

    Hi,
    Where can i get the menu paths for the below topics in SAP syste. I have searched in the system,But couldnot find the Menu Path's for the below topics.Kindly help me in finding the configuration Path for the below...
    1)Public tendering process
    2)Grants Management
    3)Tax & Revenue management
    4)Public sector accounting --> Budget formulation, preparation, execution & Monitoring.
    Thanks
    Rajitha M

    Hi,
    Check for the relevant path in IMG in Public Sector Management.  The prerequisites being configuration of Financial accounting
    sub modules.
    Best Regards,
    Sadashivan

Maybe you are looking for

  • Time Capsule & Netgear DG834GT in Modem Mode - Not working

    I've just taken delivery of a 1TB Time Capsule. I've switched my existing Netgear DG384GT modem/router into modem only mode, so routing functionality is disabled. I just want to use the DG834GT as a simple ADSL modem, whilst utilising the features (D

  • Force user to select yes/no based on criteria in another field

    Hello, I have a training subform. When the user slects a course that was taken by an employee adn if the course offers a certificate (the table with the course has the yes/no value already chosen when the course was entered in a table called course l

  • Mail Sent Items not Syncing with Rackspace Server

    Hi, My sent items are not fully syncing with my rackspace email account. Some items sent through Mail show up in the rackspace sent items and some do not. I am worried that emails are not being sent. Also, when replicating, Mail will show something l

  • How can I get Genius back. Using 6.1.2

    I downloaded update 6.1.2 and noticed that my genius feature is gone when listening to music. How can I get it back??

  • Cannot change BBM group details/setting, on BES

    Hi All, I'm newbie forgive if I wrongly put this question in this thread.. After updating to latest asia firmware (666), suddenly I cannot change BBM group detail on my torch (9800). Therefore, now I always get unwanted notification/update from new g