GetPath() vs getCanonicalPath

Can someone explain the difference between these two methods in a way that a newbie will understand? I looked at the file class ( http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html ) but i did not understand the difference very well. Thanks in advance.

Easiest way is to try it.
One difference though is that the canonical is going to look more like a standard path for the current OS.

Similar Messages

  • DefaultMutableTreeNode.getPath() returns incomplete path

    My application is quite complex, I'll try to explain the problem:
    I'm using a JTree with nodes derived from DefaultMutableTreeNode and without a
    TreeModel.
    Everytime I close a node (collapseNode) I delete all subnodes
    (node.removeAllChildren) and add a dummy-node to make the node still look
    expandable.
    Everytime I open a node (expandNode) I delete the dummy-node and add subnodes
    via node.add(newNode).
    Now here's the problem:
    If some nodes have been collapsed and expanded again, the child nodes seem to
    contain invalid data. Their getPath() method doesn't return the full path from
    root to childNode but only the childNode!
    I couldn't find similar problems in the bug database or in the forums.

    I am also facing the same problem
    -Aprajit

  • Question related to GetFile and GetPath of a URL

    Hello, i have the following code and i was wondering why GetFile and GetPath shall return the same output,
    e.g. my example here is http://wikis.sun.com/display/SunForums/Tips
    The GetPath returns : Get Path of URL /display/SunForums/Tips
    and the GetFile returns : Get file of URL /display/SunForums/Tips
    the same.
    Well it's just that i would like to use a method which is going to output only the File of a Path, in our example the output should be only Tips.
    CODE :
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.*;
    public class Main {
        public static void main(String[] args) throws MalformedURLException, IOException, Exception {
                        BufferedReader in = null;
                       try {                              //try
                              URL yahoo = new URL("http://wikis.sun.com/display/SunForums/Tips");
                             String url_string = yahoo.toString();  // Constructs a string representation of URL
                             URLConnection yc = yahoo.openConnection(); //
                             in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                             System.out.println("Get file of URL " + yahoo.getFile());                            *//it should return only Tips*
                             System.out.println("Get Path of URL " + yahoo.getPath());
                              catch (MalformedURLException ex) {
                                                                                  System.err.println("MalformedURLException" + ex);
             }Is there any method which returns only the file of a URL?
    Thanks in advance!

    new File("/display/SunForums/Tips").getName() will return "Tips".

  • Unexpected result from treenode.getPath() ???

    Hi,
    I am using Jtree in application.
    The tree is as following
    - Desktop
          -C:\
              - Folder1
              - File2
         - D:\I want to expend the node Folder1 as selected node. To do that I got the FileNode Folder1 and do
    TreePath path=new TreeaPath( folder1node.getPath() );
    int row=tree.getRowForPath(path);
    jtreetable.expend(row);
    But the problem is with the path returned. I must get the path [Desktop, C:\, Folder1] but I am getting path [Folder1].
    What I am doing wrong. Is there any other way to expend a particular node programatically ?
    Thanks

    Andy,
    You should contact support with regards to this issue. It is a known
    problem, you can reference CR042529.
    Cheers!
    Adam
    "Andy Kimbrough" <[email protected]> wrote in message
    news:3ae8b1f7$[email protected]..
    randomly I get the following error in my weblogic.log. The server stopsresponding and I get about a million of these entries, what is going on? I
    am running on Linux 6.2....<Error> <Posix Performance Pack>
    <mdw2.neomorphic.com> <myserver> <ExecuteThread: '49' for queue: 'default'>
    <><><00000><Uncaught Throwable in processSockets>java.io.IOException:
    unexpected result from poll: -1at weblogic.socket.PosixSocketMuxer.pool
    (Native Method)at weblogic.socket.PosixSocketMuser.processSocktesat
    weblogic.socket.SocketReaderRequest.executeat
    weblogic.kernel.ExecuteThread.executeat weblogic.kernel.ExceuteThread.run

  • Why got Nullpointer use getJarPath.class.getResource(".").getPath() ?

    hi,
    I have a question about the following program:
    public class getJarPath {
    public getJarPath() {
    public static void main(String[] arg) {
    System.out.println("java.net.URl->" + getJarPath.class.getResource(
    "getJarPath.class"));
    System.out.println("getPath->" + getJarPath.class.getResource(
    "getJarPath.class").getPath());
    System.out.println("getFile->" + getJarPath.class.getResource(
    "getJarPath.class").getFile());
    System.out.println("getPath with . ->"+getJarPath.class.getResource(".").getPath()); // NullPointer occured
    1. compile getJarPath.java
    D:\>D:\j2sdk1.4.2_04\bin\javac getJarPath.java
    2. run this test program with "java getJarPath"
    D:\>D:\j2sdk1.4.2_04\bin\java getJarPath
    java.net.URl->file:/D:/getJarPath.class
    getPath->/D:/getJarPath.class
    getFile->/D:/getJarPath.class
    getPath with . ->/C:/Program%20Files/exceed.nt/
    3. D:\>D:\j2sdk1.4.2_04\bin\jar cvf getJarPath.jar getJarPath.class
    4. D:\>D:\j2sdk1.4.2_04\bin\java -cp d:\getJarPath.jar getJarPath
    java.net.URl->jar:file:/D:/getJarPath.jar!/getJarPath.class
    getPath->file:/D:/getJarPath.jar!/getJarPath.class
    getFile->file:/D:/getJarPath.jar!/getJarPath.class
    Exception in thread "main" java.lang.NullPointerException
    at getJarPath.main(getJarPath.java:15)
    question:
    in step 2. why the path "." is "/C:/Program%20Files/exceed.nt/" ?
    in step 4. why NullPointerException occured?
    thank a lot
    BR

    Your output seems to indicate that all lines executed successfully, yet you say there's a NullPointerException. Which is it?

  • Url.getPath

    Hi everybody,
    I've a problem with my application web. I want to get the url of a file. I use JBoss 4.0.5. My code is:
    public static String getResourcePath(String nombre) {
             String url = null;
             try {
                  ClassLoader cld = Thread.currentThread().getContextClassLoader();
                  String path = nombre.replace('.', '/');
                  // Ask for all resources for the path
                  Enumeration<URL> resources;
                  resources = cld.getResources(path);
                  while(resources.hasMoreElements()){
                       url = resources.nextElement().getPath();
             } catch (IOException e) {
                  System.out.println(e.getMessage());
             } finally {
                  return url;
             }It is'nt finished but it's a example that I find it.
    In a main function, it's works fine but in a method not.
    Thanks!

    Have a look at the documentation. You mite have misunderstood. Try toString() or toExternalForm().
    ~Cheers
    ARN

  • JNLP FileOpenService vs JFileChooser getPath()

    In my Web Start application, I'm trying to browse a directory and remeber the path to specific folders/files. I've managed to perform all the security coding to read in files with FileOpenService, but I've read that there is no way to actually remeber the location on the host computer where that file came from.
    I would eventually like to use the mkdir() function in a selected directory and I don't want my users to have to manually select a "home" directory every time. Is there any way to get around this like JFileChooser's .getPath() function?
    Thanks Much,
    Daniel

    It should be easy enough to write a small abstract class or interface with two concrete implementations, one for each environment, so that the rest of your program doesn't care which is in use.

  • What does this do?  f.getPath().endsWith(":\\")

    Hi,
    I'm trying to figure out exactly what the piece of code at the bottom of the page does. I now that in general it returns true if the file specified is a directory that contains a file called pkgFileName(whatever that variable may be).
    The bit I can't figure out is
    if(f.getPath().endsWith(":\\"))
                return false;
            }What is the significance of files that end :\ ?
    public static  boolean isPkgFile(File f)
            if(f == null)
                return false;
            if(f.getPath().endsWith(":\\"))
                return false;
            if(!f.isDirectory())
                return false;
            else
                return new File(f, pkgFileName).exists();
        }

    Looks like it's supposed to filter out the root folders of Windows hard drives. If I remember correctly, isDirectory() returns {color:000080}false{color} when it's called on a drive.

  • A problem with Lucene In a J2EE project

    Hi everyone:
    I am newer for Lucene which is used to build a search eigneer in my J2EE project.
    But I can hardly understand how it works because of my poor English.
    So I need you help:
    * TxtFileIndexer.java
    * Created on 2006�N12��8��, ����3:46
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package classes.php.lucene;
    * @author eingmarra
    import java.io.File;
    import java.io.FileReader;
    import java.io.Reader;
    import java.util.Date;
    import org.apache.lucene.analysis.Analyzer;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.document.Field;
    import org.apache.lucene.index.IndexWriter;
    import org.apache.lucene.index.Term;
    import org.apache.lucene.search.Hits;
    import org.apache.lucene.search.IndexSearcher;
    import org.apache.lucene.search.TermQuery;
    import org.apache.lucene.store.FSDirectory;
    public class TxtFileIndexer {
         public String test() {
              return "test is ok hohoho";
          * @param args
         public String createIndex(String indexDir_path,String dataDir_path) throws Exception {
              String result = "";
              File indexDir = new File(indexDir_path);
              File dataDir = new File(dataDir_path);
              Analyzer luceneAnalyzer = new StandardAnalyzer();
              File[] dataFiles = dataDir.listFiles();
              IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
              long startTime = new Date().getTime();
              for(int i=0; i < dataFiles.length; i++) {
                   if(dataFiles.isFile() && dataFiles[i].getName().endsWith(".html")) {
                        result += "Indexing file" + dataFiles[i].getCanonicalPath()+"<br />";
                        Document document = new Document();
                        Reader txtReader = new FileReader(dataFiles[i]);
                        document.add(Field.Text("path",dataFiles[i].getCanonicalPath())); //can not pass the Netbeans IDE, maybe the Field class is not support the signature of the fuction Text anymore!!
                        document.add(Field.Text("contents",txtReader)); //can not pass the Netbeans IDE, maybe the Field class is not support the signature of the fuction Text anymore!!
                        indexWriter.addDocument(document);
              indexWriter.optimize();
              indexWriter.close();
              long endTime = new Date().getTime();
              result += "It takes"+(endTime-startTime)
                        + " milliseconds to create index for the files in directory "
                        + dataDir.getPath();
              return result;
         public String searchword(String ss,String index_path) throws Exception {
         String queryStr = ss;
         String result = "Result:<br />";
         //This is the directory that hosts the Lucene index
    File indexDir = new File(index_path);
    FSDirectory directory = FSDirectory.getDirectory(indexDir,false);
    IndexSearcher searcher = new IndexSearcher(directory);
    if(!indexDir.exists()){
         result = "The Lucene index is not exist";
         return result;
    Term term = new Term("contents",queryStr.toLowerCase());
    TermQuery luceneQuery = new TermQuery(term);
    Hits hits = searcher.search(luceneQuery);
    for(int i = 0; i < hits.length(); i++){
         Document document = hits.doc(i);
         result += "<br /><a href='getfile.php?w="+ss+"&f="+document.get("path")+"'>File: " + document.get("path")+"</a>\n";
    return result;
    the code above is from google and it works perfectly in the Lucene1.4. But it not pass the compiler by Netbeans IDE because I use Lucene2.0
    If you have some idea,plz replace these two lines' code with the correct ones.
    Thanks a lot !!

    Hi everyone:
    I am newer for Lucene which is used to build a search eigneer in my J2EE project.
    But I can hardly understand how it works because of my poor English.
    So I need you help:
    * TxtFileIndexer.java
    * Created on 2006�N12��8��, ����3:46
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package classes.php.lucene;
    * @author eingmarra
    import java.io.File;
    import java.io.FileReader;
    import java.io.Reader;
    import java.util.Date;
    import org.apache.lucene.analysis.Analyzer;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.document.Field;
    import org.apache.lucene.index.IndexWriter;
    import org.apache.lucene.index.Term;
    import org.apache.lucene.search.Hits;
    import org.apache.lucene.search.IndexSearcher;
    import org.apache.lucene.search.TermQuery;
    import org.apache.lucene.store.FSDirectory;
    public class TxtFileIndexer {
         public String test() {
              return "test is ok hohoho";
          * @param args
         public String createIndex(String indexDir_path,String dataDir_path) throws Exception {
              String result = "";
              File indexDir = new File(indexDir_path);
              File dataDir = new File(dataDir_path);
              Analyzer luceneAnalyzer = new StandardAnalyzer();
              File[] dataFiles = dataDir.listFiles();
              IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
              long startTime = new Date().getTime();
              for(int i=0; i < dataFiles.length; i++) {
                   if(dataFiles.isFile() && dataFiles[i].getName().endsWith(".html")) {
                        result += "Indexing file" + dataFiles[i].getCanonicalPath()+"<br />";
                        Document document = new Document();
                        Reader txtReader = new FileReader(dataFiles[i]);
                        document.add(Field.Text("path",dataFiles[i].getCanonicalPath())); //can not pass the Netbeans IDE, maybe the Field class is not support the signature of the fuction Text anymore!!
                        document.add(Field.Text("contents",txtReader)); //can not pass the Netbeans IDE, maybe the Field class is not support the signature of the fuction Text anymore!!
                        indexWriter.addDocument(document);
              indexWriter.optimize();
              indexWriter.close();
              long endTime = new Date().getTime();
              result += "It takes"+(endTime-startTime)
                        + " milliseconds to create index for the files in directory "
                        + dataDir.getPath();
              return result;
         public String searchword(String ss,String index_path) throws Exception {
         String queryStr = ss;
         String result = "Result:<br />";
         //This is the directory that hosts the Lucene index
    File indexDir = new File(index_path);
    FSDirectory directory = FSDirectory.getDirectory(indexDir,false);
    IndexSearcher searcher = new IndexSearcher(directory);
    if(!indexDir.exists()){
         result = "The Lucene index is not exist";
         return result;
    Term term = new Term("contents",queryStr.toLowerCase());
    TermQuery luceneQuery = new TermQuery(term);
    Hits hits = searcher.search(luceneQuery);
    for(int i = 0; i < hits.length(); i++){
         Document document = hits.doc(i);
         result += "<br /><a href='getfile.php?w="+ss+"&f="+document.get("path")+"'>File: " + document.get("path")+"</a>\n";
    return result;
    the code above is from google and it works perfectly in the Lucene1.4. But it not pass the compiler by Netbeans IDE because I use Lucene2.0
    If you have some idea,plz replace these two lines' code with the correct ones.
    Thanks a lot !!

  • Get full path

    I'm sure this one has been asked a million times before, but a search of the forums hasn't proved particularly positive - so, apologies if this is a duplicate post, but...
    How on earth does one get the full path of a file??? I mean, starting from the very root directory?
    I'm sure there must be some kind of recursive method that loops back through the directories and eventually returns a string with the full path name - but I can't figure it out. I've tried getPath(), getCanonicalPath()... etc etc, but so far with no joy...
    P.S. I need the full path as I am writing a servlet to delete files from my server and I need to pass the full path to the delete() method.... Or at least I assume that is the way to do it, and at least, writing in the path name manually works fine. The problem is that since the folders are created dynamically when the files are first uploaded, I have to find a way of retrieving the whole structure... do I not?
    A second, and possibly related problem, is that the getCanonicalPath() method returns a directory for the chosen file - but it seems to retun the wrong one! ie, it only returns /bin/file - and the file is definitely not in /bin!

    I tried that too - still didn't work. But now I think the problem is more to do with the fact that my files are stored on my server because when I try my method in a static context elsewhere on my computer it seems to work fine. Can't figure out what the problem might be...

  • Error executing batch file within web application

    Hi all,
    I am trying to execute a batch file from within my web application (struts 1.2).
    The batch file is being kept inside the 'src' folder. The batch file contains only one command to open NOTEPAD.
    The code inside my Action class is:
    URL url = getClass().getResource("/test.bat");
    java.io.File file = new java.io.File(url.getPath()) ;
    String path = file.getCanonicalPath();
    r.exec(path);
    I have deployed this on tomcat and get an error like this:
    java.io.IOException: Cannot run program "C:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\CIGTAFAPP\WEB-INF\classes\test.bat": CreateProcess error=2, The system cannot find the file specified
    The problem is not with the batch file because when I try to execute the file directly from the classes folder, it opens up the notepad editor.
    I have a specific requirement where I need to create/read this batch file from within the project structure.
    Can someone please help me with this?
    Regards

    The entire content of the file is as below:
    set javaTestProjectPath=D:\projects\CIGTAF\LRTestCases
    C:
    cd %javaTestProjectPath%
    set path=C:\Program Files\Java\jdk1.6.0_21\bin
    set classpath=%javaTestProjectPath%\bin;%javaTestProjectPath%\lib\selenium-server-standalone-2.20.0.jar;%javaTestProjectPath%\lib\testng-6.4.jar;%javaTestProjectPath%\lib\junit-4.10.jar;%javaTestProjectPath%\lib\poi-3.6-20091214.jar;%javaTestProjectPath%\lib\mail.jar
    javac -verbose %javaTestProjectPath%\src\com\core\testscripts\Mailsetup.java -d %javaTestProjectPath%\bin
    javac -verbose %javaTestProjectPath%\src\com\core\testscripts\MailAuthenticator.java -d %javaTestProjectPath%\bin
    javac -verbose %javaTestProjectPath%\src\com\core\testscripts\ReadData.java -d %javaTestProjectPath%\bin
    javac -verbose %javaTestProjectPath%\src\com\core\testscripts\ReadWriteExcelResults.java -d %javaTestProjectPath%\bin
    javac -verbose %javaTestProjectPath%\src\com\core\testscripts\SeleniumFramework.java -d %javaTestProjectPath%\bin
    java org.testng.TestNG %javaTestProjectPath%\SelXD-Config.xml -d %javaTestProjectPath%\test-output
    none of these are getting executed.
    regards
    Edited by: 887789 on May 4, 2012 1:46 AM

  • How to get the long file name from an 8.3 name in Windows.

    Because of a legacy string limitation, I have a list of files in 8.3 format. The actual files are saved with long names. How can I get the long name from the short name?
    In JavaScript, I would get a file system object and get the file object from there with the short name. Then it's no problem to get the full name. But I don't see anything in Java that matches that. ???
    Ideas?
    Frank Perry, MSEE

    Here is what I did.
    String displayName = "somefi~1.txt";
    File fO = new File("c:\\"); // I have a more involved path but that's not important here.
    String stPath = fO.getPath() + displayName;
    File fD = new File(stPath); // get the file using the short name.
    File fDc = new File(fD.getCanonicalPath()); // get another file using the cononical name
    String FulldisplayName = fDc.getName(); // get the long name from there.
    It's roundabout but it works. Since getName() on the file read with the short name only returns the name used to get the file, I open it twice. The alternative is to parse the cononical name for the file name but that's clumbsy too.
    Frank

  • Display Image in Browser

    Dear all,
    I have use the JLabel to add the ImageIcon with the filename passed under JPanel. It work on appletviewer but not in Browser.
    The appletviewer can show both ImageIcon at the top and the Text at the bottom. But the browser (IE) can only show the Text only. It seems that ImageIcon cannot be added in JLabel.
    May I missing something on the code?
    Here is my code:
    public final static DataFlavor LABEL_FLAVOR =
    new DataFlavor(JLabel.class, "Label Instances");
    public final static DataFlavor LOCAL_LABEL_FLAVOR = new DataFlavor(
    DataFlavor.javaJVMLocalObjectMimeType +
    "; class=javax.swing.JLabel", "Local Label");
    protected JLabel getLabelFromFile(File f) {
    //ImageIcon icon = new ImageIcon(f.getAbsolutePath());
    ImageIcon icon = new ImageIcon(f.getName());
    JLabel label = new JLabel(icon);
    label.setText(f.getName());
    label.setHorizontalTextPosition(JLabel.CENTER);
    label.setVerticalTextPosition(JLabel.BOTTOM);
    label.addMouseListener(this);
    label.addMouseMotionListener(this);
    return label;
    Thanks a lot!
    Peter

    Hi,
    Theres nothing wrong in ur code.
    the only problem is in IE's version of java(WFC) the File class doesnot have a getAbsolutePath() mehtos instead it uses the getFullPath() method which isn't there in the actual java class.Thats the reason why ur code isn't working on IE.Infact IE(WFC) doesn't implement any of the following methods
    getPath()
    getCanonicalPath()
    getParent()
    getparentFile()
    createNewFile()
    etc
    Maybe u could pass the path of the Image file as a parameter to the applet and then try to display it on the JLabel.
    Hope that helps.
    Regards,
    Partha

  • Problem with space and toURI()

    Hi,
    My program is working #1 when I create a MediaLocator like that:
    mediaLocator = new MediaLocator(file.toURL());
    But I know that toURL is depreciated so I changed it to
    mediaLocator = new MediaLocator(file.toURI().toURL());
    And now, when my path contain spaces, it create a folder with %20 instead of space...
    For exemple:
    c:\Documents%20and%20Settings
    instead of
    c:\Documents and Settings
    Thanks for help!

    This works for me - with my videos in
    C:\Workspace\JMF\src\\jmf\My videos
         private void playFile(File f) throws Exception{
            System.out.println("file - '" + f.getPath()+ "'");
            MediaLocator mL= new MediaLocator("file:" + f.getCanonicalPath());
            DataSource dS = Manager.createDataSource(mL);
            Processor proc = Manager.createProcessor(dS);
            proc.addControllerListener(this);
            proc.configure();
         }

  • How to know the directoy from a file

    I have a file created in java , how do i get the directoypath on an easy way with the name of the file. Is there a methode? Or to I have to play with strings?

    If you created a file you must hava a File object. The File object has a number of methods to obtain the full path of the file, check out: getAbsolutPath, getCanonicalPath, getParent, getPath, etc.

Maybe you are looking for

  • Best Buy, what is a loyal customer worth?

    I have never written this type of message before but I felt this to be important for Best Buy to read. I was in retail for 37 years. I started out stocking shelves and ended my career a Senior Director. What I experienced in the last 3 days over a ce

  • Menu fonts all turn into boxed capital "A"s

    At some point last night, while I was working on my 10.4.9 PowerMac G4, something happened and my menu fonts all turned into some glyph that looks like a capital "A" inside of a box. All of the text on the desktop, menu bar, window titles, and the le

  • Is there a way to disable the option to save files in the cloud for a companies user base in the new subscription model??

    Our corporation is mandated by privacy laws within provincial legislation that prevents us from using cloud based storage outside of our province for the storage of data.  We are unable to continue using Adobe products based on the new subscription b

  • DB deployment failed in Plan

    Hi: I installed Essbase and configured and tested and everything is ok. I installed Hyperion planning and when I tried to configure the database through configuration utility, I get the following error. (Oct 12, 2008, 11:28:55 AM), com.hyperion.cis.c

  • Send this page script

    I am looking for a send this page form like the one found here: http://www.adobe.com/products/creativesuite/web/standard/?xNav=WS is this script available anywhere? Thanks