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