Java Java Development Use tips _ Get a file path in the current project

Source: Internet
Author: User

The following is a small instance, and the comments are clear but sufficient to illustrate the problem.

1. Instance Code
1  Public classTestmain {2     3      Public StaticString project_name = "/test/";4      Public StaticString file_name = "Src/com/test/newfile.xml";5     6      Public Static voidMain (string[] args)throwsIOException {7         //gets the path of the current class8String ClassPath = Testmain.class. GetResource (""). GetPath ();9         //get the project name where it is locatedTen         intindex =Classpath.indexof (PROJECT_NAME); One         //intercepting project root directory AString ProjectPath = classpath.substring (0, index); -System.out.println ("Path:" +projectpath+project_name+file_name); -BufferedReader BufferedReader =NewBufferedReader (NewFileReader (projectpath+project_name+file_name)); theString str =NULL; -         if(str = bufferedreader.readline ())! =NULL){ - System.out.println (str); -         } +     } -}
View Code

The key is to use it flexibly according to the actual demand.

2. Implementation results

  

Note: newfile.xml is an XML file that is currently in a similar directory.

3. Thinking

Why not just write the absolute path?

A: In our actual development process is basically a team development, with the help of SVN and other code synchronization. We cannot guarantee that the storage path of each local project is consistent, some may be in the D drive, some in the E drive. The above approach ensures that the path ahead of the project is dynamically fetched, and that the owner's local project storage location is different and does not affect the execution of our code at all. Otherwise, there will be problems.

Java Java Development Use tips _ Get a file path in the current project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.