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)?

Similar Messages

  • How to read the content of ms-word file use pure java???

    how to read the content of ms-word file use pure java???

    hi,
    check this: http://jakarta.apache.org/poi/

  • Finding the exact path to a newly created file.

    Hello,
    In my program I create a new file using a BufferedWriter. This, as you most certainly know, creates the file in the current directory. I'd like to know how do I find out the exact path of the file I just created?
    Example: the program is being run from C:\Java. The program creates the file test.txt. How do I figure out that it's C:\Java\test.txt if I don't know for sure what directory the program is being run from?
    Thanks,
    -Kain

    Heh. I feel pretty dumb now. I had been looking at that exact method for about a week now but thinking it wouldn't be as easy as it sounds. After trying it it was pathetically easy. Guess I should always try things first before deeming it impossible by those means.

  • Function that finds the absolute path of a file

    Hi,
    I'm creating an application using the SDL framework.
    The following code gives me the absolute path for the file "caisse.jpg", which is located in my application bundle. Then, I can use the value of "cstrURL" to load the image with IMG_Load(cstrURL);
    #import <CoreFoundation/CoreFoundation.h>
    int main(int argc, char *argv[])
    CFURLRef url = CFBundleCopyResourceURL( CFBundleGetMainBundle(),
    CFSTR("caisse"),
    CFSTR("jpg"), //extension du fichier
    NULL );
    const char* cstrURL = CFStringGetCStringPtr(
    CFURLCopyFileSystemPath(url,kCFURLPOSIXPathStyle),
    CFStringGetSystemEncoding()
    printf("URL: %s", cstrURL);
    return EXIT_SUCCESS;
    But I have many files to load for my application. I tried to create a function that would take as parameter informations about the image, and then automatically find the absolute path of this image.
    ( void imgPath(char name[], char ext[], char destination[] ---> name = "image", ext = "jpg", destination is a variable in which the function puts the absolute path of the file)
    How can I do that? What bugs me is the use of the CFSTR macro in the code I have...
    Thank you very much
    FRANKY

    The CFSTR macro can only use a constant string as parameter, not a variable one.
    You can use instead CFStringCreateWithCString if the parameter is a C String (char *).
    Additionaly, I think the input parameters of your imgPath function must be of char* type, not char. And the output parameter char** (but it would be easier to know with the function source code).

  • How to find the physical path of a file

    Usually, one can use absFileNmae() method to find the path of a file in Java. The problem is that it may only return a mapped path when a Servlet or JSP is running in a special server. For example, when I run a servlet "MyProgram" in JRun, absFileName() only returns "c:\JRun\jsm-default\MyProgram", which is just a mapped path, not a real physical path.
    By the way, in ASP, one can use server.mapPath("MyASPProgram.asp") to obtain the real physical path of the file.
    Your solution is welcome.
    YC

    Usually, one can use absFileNmae() method to find the path of a file in Java. The problem is that it may only return a mapped path when a Servlet or JSP is running in a special server. For example, when I run a servlet "MyProgram" in JRun, absFileName() only returns "c:\JRun\jsm-default\MyProgram", which is just a mapped path, not a real physical path.
    By the way, in ASP, one can use server.mapPath("MyASPProgram.asp") to obtain the real physical path of the file.
    Your solution is welcome.
    YC

  • Finding the physical path of a file

    I'm developing a JSP webapp on www.mycgiserver.com and I need to open a XML file....but the standard method of
    ServletContext sc = getServletConfig().getServletContext();
    String realPath = sc.getRealPath("data\\repositoryData.xml");
    seems not to work. It gives me
    Real Path of data\repositoryData.xml: /usr/local/resin/doc/data/repositoryData.xml
    Which ends up giving me null pointer exceptions on my Document objects. I assume that means it's not finding any file at that location. What am I doing wrong?

    try:
    String rootContext = getServletContext().getRealPath();
    String servletPath = request.getServletPath();
    realPath = rootContext + servletPath //however, it's what ever the servlet-mapping element
    in your deployment descriptor is set too

  • Getting font files used by Java

    Hi everyone,
    I am writing an application which allows the user to use different fonts available on the system. When saving a document in this application, I would like to include the fonts with the document, rather than just references (in case the document is transferred to another system that doesn't have the fonts installed).
    Presumably this is a simple case of finding the location of each font file used within the document and then copying it to the folder containing the document (then the document can use the local fonts).
    However, I wasn't able to find a (system-independent) way to determine where a given font is located on the system. Can anyone point me in the right direction for doing this?
    Thanks,
    Bren

    _______Please Join____www.fabgabs.com________
    ___the first social navigation site________
    ___build by students of our country using java JSP J2ee___
    Please Join and review all java developers
    ____You can watch hollywood and indian movies Here and can play with maps____
    Thankyou

  • How to read an XML file into a java program?

    hi,
    i want to load the following very simple xml file in my java program.
    <root>
    <weblogic>
    <url value="t3://192.168.1.160:7001" />
    <context value="weblogic.jndi.WLInitialContextFactory" />
    </weblogic>
    </root>
    I am getting the error: " Line=1: cvc-elt.1: Cannot find the declaration of element 'root'."
    What might be the problem can anyone help me out.
    My java class code is:
    public class BIXMLReader {
    /** All output will use this encoding */
    static final String outputEncoding = "UTF-8";
    // Parses an XML file and returns a DOM document.
    // If validating is true, the contents is validated against the DTD
    // specified in the file.
    public static Document parseXmlFile(String filename, boolean validating) {
    try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setValidating(validating);
    // Create the builder and parse the file
    System.out.println("filename = " + filename);
    DocumentBuilder db = factory.newDocumentBuilder();
    // Set an ErrorHandler before parsing
    OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, outputEncoding);
    db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
    Document doc = db.parse(new File(filename));
    System.out.println(doc.toString());
    return doc;
    } catch (SAXException e) {
    System.out.println("A parsing error occurred; the xml input is not valid. " + e.getMessage());
    } catch (ParserConfigurationException e) {
    System.out.println("Parser configuration exception has occured");
    } catch (IOException e) {
    System.out.println("IO Exception has occured " + e.getMessage());
    return null;
    // Error handler to report errors and warnings
    private static class MyErrorHandler implements ErrorHandler {
    /** Error handler output goes here */
    private PrintWriter out;
    MyErrorHandler(PrintWriter out) {
    this.out = out;
    * Returns a string describing parse exception details
    private String getParseExceptionInfo(SAXParseException spe) {
    String systemId = spe.getSystemId();
    if (systemId == null) {
    systemId = "null";
    String info = "URI=" + systemId +
    " Line=" + spe.getLineNumber() +
    ": " + spe.getMessage();
    return info;
    // The following methods are standard SAX ErrorHandler methods.
    // See SAX documentation for more info.
    public void warning(SAXParseException spe) throws SAXException {
    out.println("Warning: " + getParseExceptionInfo(spe));
    public void error(SAXParseException spe) throws SAXException {
    String message = "Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);
    public void fatalError(SAXParseException spe) throws SAXException {
    String message = "Fatal Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);
    }

    ok thanks, i can get the elements, but why did it not validate it?
    I want to read the child nodes of "weblogic" not by their name but by their index. Because i dont want to confine the reader so i want to read all the child nodes of weblogic (looping over them). i m doing the following but its not returning me the correct result and giving me the wrong count of child nodes.
    Element elementNode = (Element)doc.getElementsByTagName("weblogic").item(0);
    NodeList nodeList = elementNode.getChildNodes();
    int length = nodeList.getLength();
    System.out.println("length = "+ length); // the length its giving is 5 but i shuld get only 2
    for(int i=0; i < length; i++) {
    Element elmChild = (Element) nodeList.item(i);
    System.out.println(elmChild.getAttribute("value"));
    what might be the problem?

  • How do I find out the exact path of each and every file that LabVIEW finds and loads into memory for a given top level vi?

    How do I find out the exact path of each and every file that LabVIEW finds and loads into memory for a given top level vi? There is probably a trivial, easy way to get this info, but I have not yet found it!  Thanks..

    Or if you want to grab all the paths programatically, try the attached VI.
    Open the top level that you want all the paths from and close all others, then open the
    attached and run it. It will return an array of all the VIs that the VI
    in question uses, including vi.lib VIs. You can filter these as well if
    you like.
    Ed
    Message Edited by Ed Dickens on 08-01-2005 07:01 PM
    Ed Dickens - Certified LabVIEW Architect - DISTek Integration, Inc. - NI Certified Alliance Partner
    Using the Abort button to stop your VI is like using a tree to stop your car. It works, but there may be consequences.
    Attachments:
    Get all paths.vi ‏29 KB

  • I have files that freeze my programs whenever I try to open ANY file. Is there a way to find the exact files causing the crash?

    I have files that are freezing my programs (adobe; after effect and photoshop, as well as maxon cinema 4d). Whenever I try to import ANY file from within the program it doen't even let me select the file I need before freezing. I have moved all files off my desktop and into my dropbox, and it now allows me to import files/search for files on the desktop but NOT dropbox, once I go to dropbox it freezes again. I am assuming there are files within dropbox now that are crashing my programs. The problem is I have a lot of files in there and would like to remove the corrupt ones so that I can use my programs without freezing. Is there a way to find the exact files causing the crash?
    This has happened a couple of times and each time I have to move all my files off my desktop, so there must be a type of file doing this, I just don't know what files they are.
    Mac Book Pro 15" running OSX 10.9
    Processor  2.3 GHz Intel Core i7
    Memory  16 GB 1600 MHz DDR3
    Graphics  Intel Iris Pro 1024 MB
    ANY help would be greatly appreciated! It is making it really hard to get work done. THANKS!

    This error sounds to me like you have/had BootCamp Windows installed and then removed, posible ?
    If so (and even if not so), try restating your MBA while holding down the alt/option-key until you get to the Boot Selection Screen.
    Choose to boot OSX.
    Once in OSX go to System Preferences then Startup Volume and set your OSX to be the default.
    Hope it helps
    Stefan

  • 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..

  • How do I find the address -thread - of a file. I used to use spotlight but after switching to Mountain Lion it no longer gives me this.

    How do I find the address -thread - of a file. I used to use spotlight but after switching to Mountain Lion it no longer gives me this.

    Hold Command-Option while pointing to an item in the Spotlight list. Or Command-Click will show the item in the Finder.

  • How 2 get the path of a file Using jsp

    how 2 get the path of a file Using jsp
    i have tried getPath...but i'm geting the error
    The method getPath(String) is undefined for the type HttpServletRequest
    any idea how 2 get the path of a file

    You need ServletContext#getRealPath().
    API documentation: http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

  • Oracle OAF Find the Document Path Using JDR Tables or JDR_UTILS API

    Hi,
    I found duplicate records in JDR_PATHS table for a Particular OAF Page. I need to find the complete path of these documents,so that i can delete the one which i don't want
    using the jdr_utils.deletedocument.
    Appreciate it if anyone can advise on how to identify the paths for the a page so that I can delete the document I do not want.  Any other ideas to delete the extra document would be welcome.
    Thanks
    Sai

    Sai,
    Duplicate records in JDR_PATHS does not mean they are duplicate records, page names may be same.
    But the hierarchy of the page is different, don't be in a hurry to delete the document.
    try to find the information from this :
    Learn Oracle Applications With Me: MDS in Oracle Applications, OAF
    Regards
    Sridhar

  • I have one folder with several projects all of which Aperure can not find the original.  I do not use referenced files.  I can't make any adjustments like cropping etc. What can I do to print any of these photos?

    I have one folder with several projects all of which Aperure can not find the original.  I do not use referenced files.  I can't make any adjustments like cropping etc. What can I do to adjust or print any of these photos?  IO have no ther projects with this problem.  My Aperture Library is automatically saved to two external drives.
    Dick Koos

    I have one folder with several projects all of which Aperure can not find the original.
    Have you checked inside your Aperture library, if the original files are still there?
    Try to find out, when the images in those projects have been originally imported, then open the Aperture library by ctrl-clicking it and using the command "Show package contents" from the pop-up menu. In the window that will open, select the folder "Masters" and browse the contents. You need to find the subfolder with the year you imported the images, then the folders with the month and the day.
    Are your original files still there?
    If yes, copy them to a folder on your desktop for safe-keeping, and then try, if repairing the permissions and the other Furst Aid tools will help Aperture to connect to these missing files again - see this link:  Repairing and Rebuilding Your Aperture Library: Aperture 3 User Manual
    If the First Aid Tools don't help, then check, if Aperture has moved the missing images to a "recovered folder". If not, reimport the images, you saved to your Desktop and use the Lift&Stamp tool to transfer any adjustment and captions to your reimported images.

Maybe you are looking for

  • Pdf i cant access

    I don't understand what I have done, but my pdf wont open . It says  error opening document access denied

  • Mac Mini Server won't go to sleep!

    Like a naughty child, my Mac Mini server (i7 2Ghz, OS X 10.7.3) won't go to sleep. I use it as a personal computer, not a server, and I like to put it to sleep at night. But about 20 seconds after going to sleep, it wakes up again. I've shut off all

  • Memory handling for big footage, wrong settings, bug?

    Hi I am getting huge time differences in rendering, a full res render takes ca 100 times longer than a half res, where I would normally expect maybe 4 times longer. Here's the details: I'm making an 30 sec animation in NTSC, the material is high reso

  • Virus-like activity on my iphone browser? No JB!

    hi, I use an iphone 5 with ios 8 with NO Jailbreak. when I browsing on safari I am getting redirected to a fake and fraudulent-looking website. On a pop-up, reads the message "you have been on some forbidden websites. You have to pay 100 euro." This

  • Airport Express as a client on a D-Link 624 WPA2 network

    Hi everyone! I took the plunge and bought an iPod and I'm totally hooked. Then I got an Airport Express. I had some issues getting it connected as a client, so I tried it with no encryption or security whatsoever (not even WEP) and it worked brillian