Parsing "~" in the File class

On the same (Linux) computer, sometimes,
new java.io.File("~").isDirectory()
returns 'true' and, sometimes, it doesn't. To be clearer, in some programs it returns true and in other programs it doesn't.
This is driving me crazy!
PS. I know I should be using System.getProperty("user.home") but ...

mumbles wrote:
On the same (Linux) computer, sometimes,
new java.io.File("~").isDirectory()
returns 'true' and, sometimes, it doesn't. To be clearer, in some programs it returns true and in other programs it doesn't.If it returns true, then in the current directory (system property "user.dir") there is a directory called "~". When you type something like ls ~, it's the shell (bash, zsh, etc.), not the file system, nor the OS, nor java.io.File, that's expanding the ~ into /home/mydir or whatever.
PS. I know I should be using System.getProperty("user.home") but ...But what? Why not do it the right way?

Similar Messages

  • The "File" class does not accept my paths

    Hi ,
    I need yo creat an instance of a directory/file using the File class , but it seems to not recognize my paths:
    using :
    File f = new File("c:/Dir1/dir2/file.ext");
    or:
    File f = new File("c:/Dir1/dir2");
    allthow all do exist , when I use the f.exists() it returns false !!!!
    what is missing ?
    thanks , Adaya .

    Hi
    Found my problem - it wasn't the backslahes (one can use both ways '\\' or'/') it was a realy stupid problem..
    thanks any way ,
    Adaya .

  • The File class ignores the file.separator system property?

    I am saving the pathname of a file to a String using:
    String pathString = myfile.getAbsolutePath();
    This gives me e.g. "D:\Java\Projects\myfile.txt" on Windows XP
    If I want to save this value to a properties file, then load it in a new invocation of the program, this string will not be recognised as a valid pathname because of the backslashes.
    So I want to use forward slashes as the file separator char.
    I tried:
    System.setProperty("file.separator","/");
    However, this setting seems to be ignored by the File class, as I still get the same string with backslashes from the getAbsolutePath() method.
    Can anyone help please?

    Yeah... I've used that before. Never recalled having problems. I can't, however, recall if there were file paths saved.
    Just tested with this:
    import java.io.*;
    import java.util.*;
    public class Props {
         public static void main(String[] args) {
              try {
                   Properties p1 = new Properties();
                   p1.put("file", new File("C:\\test\\Props.java").getAbsolutePath());
                   FileOutputStream out = new FileOutputStream("Props.properties");
                   p1.store(out, null);
                   out.close();
                   FileInputStream in = new FileInputStream("Props.properties");
                   Properties p2 = new Properties();
                   p2.load(in);
                   System.out.println("p1: " + p1.getProperty("file"));
                   System.out.println("p2: " + p2.getProperty("file"));
              } catch(Exception e) {
                   e.printStackTrace();
    }created this:
    #Tue Jun 21 10:53:38 EDT 2005
    file=C\:\\test\\Props.java

  • Parsing an xml file using xerces DOM  parser

    Hi
    I want to parse a simple xml file using DOM parser.
    The file is
    <Item>
         <SubItem>
              <title>SubItem0</title>
              <attr1>0</attr1>
              <attr2>0</attr2>
              <attr3>0</attr3>
         </SubItem>
         <SubItem>
              <title>SubItem1</title>
              <attr1>1</attr1>
              <attr2>0</attr2>
              <attr3>0</attr3>
         </SubItem>
         <SubItem>
              <title>SubItem2</title>
              <attr1>1</attr1>
              <attr2>1</attr2>
              <attr3>0</attr3>
              <SubItem>
                   <title>SubItem20</title>
                   <attr1>2</attr1>
                   <attr2>1</attr2>
                   <attr3>0</attr3>
              </SubItem>
              <SubItem>
                   <title>SubItem21</title>
                   <attr1>1</attr1>
                   <attr2>1</attr2>
                   <attr3>0</attr3>
              </SubItem>
         </SubItem>
    </Item>
    I just want to parse this file and want to store the values in desired datastructures,
    I am trying using DOM parser, since it gives a tree structure, which is ok in this case.
    public void init()
              InputReader ir     =new InputReader("Habsys");
              Document      doc     =ir.read("Habitat");
              System.out.println(doc);
              traverse(doc);
    private void traverse(Document idoc)
              NodeList lchildren=idoc.getElementsByTagName("SubItem");
              for(int i=0;i<lchildren.getLength();i++)
                   String lgstr=lchildren.item(i).getNodeName();
                   if(lgstr.equals("SubItem"))
                        traverse(lchildren.item(i));
    private void traverse (Node node) {
    int type = node.getNodeType();
    if (type == Node.ELEMENT_NODE)
    System.out.println ("Name :"+node.getNodeName());
    if(!node.hasChildNodes())
    System.out.println ("Value :"+node.getNodeValue());
    NodeList children = node.getChildNodes();
    if (children != null) {
    for (int i=0; i< children.getLength(); i++)
    traverse (children.item(i));
    But I am not getting required results, a lot of values I am getting as null
    Could anybody tell me how to retrieve the data from the xml file, I simply want to read data and store it in data structures. For eg, for tag Subitem with title as ' SubItem1' has attr1 as '1', attr2 as'0' and attr3 as '0'.
    Thanks
    Gaurav

    Check This Sample Code....
    public void amethod(){
    DocumentBuilderFactory dbf = null;
    DocumentBuilder docBuilder = null;
    Document doc = null;
    try{
         dbf = DocumentBuilderFactory.newInstance();
         db = dbf.newDocumentBuilder();
         doc = db.parse(New File("path/to/your/file"));
         Node root = doc.getDocumentElement();
         System.out.println("Root Node = " + root.getNodeName());
         readNode(root);
    }catch(FactoryConfigurationError fce){ fce.printStackTrace();
    }catch(ParserConfigurationException pce){  pce.printStackTrace();
    }catch(IOException ioe){  ioe.printStackTrace();
    }catch(SAXException saxe){  saxe.printStackTrace();
    private void readNode(Node node) {
    System.out.println("Current Node = " + node.getNodeName());
    readAttributes(node);
    readChildren(node);
    private void readAttributes(Node node) {
    if (!node.hasAttributes())
         return;
    System.out.println("Attributes:");
    NamedNodeMap attrNodes = node.getAttributes();
    for (int i=0; i<attrNodes.getLength(); i++) {
    Attr attr = (Attr)attrNodes.item(i);
    System.out.println(attr.getNodeName() + " => " + attr.getNodeValue());
    private void readChildren(Node node) {
    if (!node.hasChildNodes())
         return;
    System.out.println("Value/s:");
    NodeList childNodes = node.getChildNodes();
    for (int i=0; i<childNodes.getLength(); i++) {
    Node child = (Node)childNodes.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
    readNode(child);
    continue;
    if (child.getNodeType() == Node.TEXT_NODE) {
    if (child.getNodeValue()!=null)
    System.out.println(child.getNodeValue());

  • File class

    Hello, I have a curiosity question, why doesn't the File+ class provide a method for retrieving the basename of a file excluding the suffix? For example, for the path
    _"C:\some\file\path\filename.ext"_
    File*.+getName+() returns the string "*filename.ext*"; however, it would be nice if there was a convenience method such as, File*.+getName2()+, for instance, that returned "*filename*".
    I know it is trivial to do this programmatically, but I was surprised that this method was missing from File* class. Is there a particular reason for this becauseI do this all the time in Unix and Windows.
    Thanks.

    I see your point and it's vaild; however, in Unix I use the command "basename ext" specifying the suffix. I was thinking that they could have done the same thing, for instance, create the following method;
    "*+public String getName( String sSuffix )+*"
    One would have to specify the suffix you want filtered out of the filename. Then, the following code segment;
    File file = new File ( "c:\some\file\path\filename.ext" );
    System.out.println( file.getName() );
    System.out.println ( file.getName ( "ext" ) );would print the lines;
    filename.extfilename>
    Problem solved and it would be a nice convenience method :)
    Thanks

  • UrlLoader - replace with File class to access external assets

    Hi.
    Just reading up on the File class more than anything because I want to develop on mobile devices. Can I substitute all my urlLoader classes with the File class for my games on the web.
    var prefsFile:File = File.applicationDirectory;
    prefsFile = prefsFile.resolvePath("preferences.xml");
    I feel like this may be a stupid question but I have to ask.
    Cheers

    yes, but you probably don't want to use the applicationDirectory because of security issues.
    and is there some reason you can't use your urlloaders?

  • Moving the files from one directory to another.

    It seems that this would be simple but I am not able to do it easily. I just want to move files from one directory to another directory. I tried the file class renameTo as in the following...
    File fFrom = new File("C:\\uhin\\batch\\outgoing");
    File fTo = new File("C:\\uhin\\batch\\outgoing\\back");
    fFrom.renameTo(fTo);
    but this doesn't seem to work. I have tried deleting the directory and then recreating it but this doesn't seem to work as in.
    fTo.delete();
    fTo.mkdir();
    any ideas ?
    thanks
    kris.

    That code you have there tries to rename the directory from C:\uhin\batch\outgoing to C:\uhin\batch\outgoing\back. I'm not sure if you can rename directories in general, but even if you can that particular renaming wouldn't work.
    However you didn't want to rename the directory in any case. You need to use a File method called listFiles (if I recall correctly... check the API documentation) which returns an array of File objects, representing all the files in that directory. Then loop through that array, and for each File in it, (1) create a new File object with the new name, and (2) call renameTo() to rename the file.

  • Stop Sax Parser in the middle of parsing

    Hi all,
    I am using Sax Parser.
    I want to stop the parsing after finding a specific element for the first time. I have thought on two ways -
    1. Throwing an exception - Pros- clean, short. Cons - ugly it is not Exception.
    2. adding a flag and if statement in the begin of each event-driving method checking whether I have found the element or not - Cons - I am still wasting lots of time on parsing all the file and doing nothing.
    Does anybody know any better way of stopping the Sax Parser?

    I've never tried to do this. The two options you have provided should work. I don't know of any others. The second option could be modified to use a Strategy pattern. Make a Handler that jst defers to your real handler. Once you hit the element tha you need, swap out your handler with one that has an empty implemetation.

  • Upload all the files in a directory

    Hi,
    I have searched in forum for a solution to my problem (Upload all the files contained in a certain directory) but all I've found is solutions to upload a single file using the bean JspSmartUpload. I had myself used this bean to uploads files to an server, but files choosed by the user with the <input type="file">. What I'm wanting know is different and I can't find a solution to it. I've tried to change the jspsmartupload to do this but I'm having no success..
    Anyone can help?
    Thanks in advance,
    Nuno.

    I don't believe there's any support in pure html forms to accomplish this.
    The File class has a listFiles() method, that will return an array of all the files in a directory. As this code must run on the client machine, you will need to write an applet to accomplish this. You will also have to worry about the security sandbox, and sign your applet.
    To get each file to the server you will need to create a URL object, openConnection on it, set up a multipart form POST to it, and transfer the files, one by one.

  • RenameTo() method in File.class

    I want to know in which platforms the renameTo() method in the File class actually move the file to the detination directory. I have checked with Windows. It does move the file to the targetted directory. What about other platforms??

    YoungWinston wrote:
    supratim wrote:
    My concern is if I am sure that that the renameTo() succeeds in doing its thing[By doing a simple renameTo() on a file and check if it is getting moved],
    can it supply me any perfomrmance boost compared to normal stream based copying and then deleting the file.I think you'll have to describe what you're trying to do, and what you think your alternatives are, a bit better.
    You never know, somebody may have a '3rd way' which is superior to either.
    WinstonMost certainly there may be a lot more ways. All I want to know does the renameTo() method works more faster than the normal stram based copying[which includes creating InputStream  and OutputStream] which looks ugly[catching FileNotFoundException,IOException etc]. Well don't take the "ugly" word otherwise, this just waht I think.
    I have learned that if FileChannel s are used it, it can boost up the copying speed compared to the stream based copying. But channels are normally used where a bigger size of file needs to be transferred. Should I use channels for faster io.
    I am so concerned about the speed because it is preciously what I need to do in my current work. I have to do a lot of io[file moving,copying etc] and my files are also not very big[max 3MB,min 3KB], and I want to know the best way to achieve this in a perfect and of course faster way.

  • File class question

    Hi all,
    I've been playing with the File class (as a way of learning about it) and am confused about the behaviour of the following code.
    This class is uses recursion as a way of getting a file structure.
    import java.io.File;
    public class FileTest {
        public static void main(String[] args) {
            if (args.length == 0) {
                return;
            File file = new File(args[0]);
            processFileList(file);
        public static void processFileList(File f) {
            if (f.isDirectory()) {
                System.out.println("found directory: " + f.getName());
                String fileList[] = f.list();
                for (int i=0; i < fileList.length; i++) {
                    File newF = new File(fileList);
    if (newF.isFile()) {
    System.out.println("Found file in list: " + newF.getName());
    } else {
    System.out.println("Found new directroy is list: " + newF.getName());
    processFileList(newF);
    } else {
    System.out.println("Found file: " + f.getName());
    The command line I use is java FileTest testdir
    The output from the code is:
    found directory: testdir
    Found file in list: FileTest.class
    Found file in list: Hello.class
    Found file in list: LogTest.class
    Found new directroy is list: testdir2
    Found file: testdir2
    The file structure being used is testdir, which contains the three class files and a directory called testdir2. testdir2 contains some java files.
    I don't understand why testdir2 is recognised as not being a file, but is not recognised as being a directory. I changed the code to use isDirectory() rather than isFile(), but the results were similar, testdir2 is not recognised as a directory.
    Any ideas? Thanks,
    dan

    When you instantiate the class java.io.File from a String you should use a pathname or depict the parent directory as well as the abstract file name. Or you could use the method listFiles() of the File class.
    File[] fileList = f.listFiles();

  • How to know the size of the file

    hi all ,
    how can I know the file Size (like 23K, 45K, 0K)..
    if anyone knows please help me
    thanks

    Just use the length of the File class...

  • File class using URI in a web server.

    How do I reference a file or directory on a web server using the File class?
    For example, if the URL is http://localhost:8080/foo and I want to access the images directory, how would I do it?
    This is what I've tried:
    URI uri = new URI("http",null,"foo",8080,"/foo/images",null,null);
    File file = new File(uri);
    I am getting an exception: java.lang.IllegalArgumentException: URI scheme is not "file"
    uri.toString() looks good. File just doesn't seem to like a directory within a web server. I don't think I'm going to know the absolute path when I move to the actual web server.

    Try to use  search FTP in se37 or checkout the below FM
    CALL FUNCTION 'EPS_FTP_MPUT'
      EXPORTING
        RFC_DESTINATION            =
    *   FILE_MASK                  = ' '
    *   LOCAL_DIRECTORY            = ' '
    *   REMOTE_DIRECTORY           = ' '
    *   OVERWRITE_MODE             = ' '
    *   TEXT_MODE                  = ' '
    *   TRANSMISSION_MONITOR       = 'X'
    *   RECORDS_PER_TRANSFER       = 10
    *   MONITOR_TITLE              =
    *   MONITOR_TEXT1              =
    *   MONITOR_TEXT2              =
    *   PROGRESS_TEXT              =
    * IMPORTING
    *   LOCAL_DIRECTORY            =
    *   REMOTE_DIRECTORY           =
    *   LOCAL_SYSTEM_INFO          =
    *   REMOTE_SYSTEM_INFO         =
    * TABLES
    *   FILE_LIST                  =
    * EXCEPTIONS
    *   CONNECTION_FAILED          = 1
    *   INVALID_VERSION            = 2
    *   INVALID_ARGUMENTS          = 3
    *   GET_DIR_LIST_FAILED        = 4
    *   FILE_TRANSFER_FAILED       = 5
    *   STOPPED_BY_USER            = 6
    *   OTHERS                     = 7
    IF SY-SUBRC <> 0.
    * Implement suitable error handling here
    ENDIF.

  • Is the File object part of JFrame?

    Hi,
    I am not sure about this
    Do I need to inherit from JFrame in order to get the File class?
    I want to have "File" in a standalone class..
    Any ideas?
    Thanks
    Jack

    luckiejacky wrote:
    Do I need to inherit from JFrame in order to get the File class?Look at the File API and tutorials to answer this question
    http://java.sun.com/javase/6/docs/api/java/io/File.html

  • File Class in Web Applications

    Hallo, i am creating a web Application but i need to know the fullpath of a file. I see that in the web based application i can call that FileReference class but with this class i can only get the name of a file and not the fullname. I can do this with the File Class which is avaible in Air Applications. How can i do it with my FlashPlayer application??....
    Thanks for all
    Max

    You can't get that with FileReference on the web (Security reasons). It was
    possible to get it with an HTML form and Javascript but I am not sure Firefox 3
    is still delivering the full path. Also not sure it works in all the browsers.
    C

Maybe you are looking for

  • Itunes won't start unless a cd is in the cd tray.

    Hi all, I have moved last week from WinXP to Windows 7 and since then iTunes (the last version, 9.0.1) refuses to start, unless I have a cd (data or music doesn't matter) in the cd tray. The error that I get says: "Quick Time not found. Quick time is

  • User hot and Rman hot backup

    During user mode hot backup lots of redo gets generated as the entire block is written when any changes are made to a block which is in hot backup mode.But during Rman hot backup less redo are generated why is this so and whatz the logic invloved? an

  • How to "skip" part of a signal

    Hey everyone, I'm still very new to LabVEIW I'm writing a code to control a pair of mirrors which will scan across a designated area, one on x-axis and on the y-axis. The movement is defined by two triangle waves (for simplicity at the time being, I

  • Imovie 13 crash!! please help

    Hi, i wanna edit a video, imovie normal opnened, when select the file and click  import nothing happened and crash the program. I restart the application and the interfase appears weird, my events and proyects are not visible and i can´t do anything

  • Connecting with other designers

    How do I connect with other designers through the Creative Cloud? I currently purchased this product, hoping that there would be a way I would be able to connect with other designers around the world and share ideas, and bounce questions off of. This