In development tools, for example, a Java file name is called Cat. java.
Right-click cat. Java and choose Properties> resource options. You can see path:/myhibernate/src/cjq/hibernate/tutorial/EG/domesticcat. Java
Type: file (Java source file)
Location: D: \ eclipseworkspace \ myhibernate \ SRC \ cjq \ hibernate \ tutorial \ eg \ domesticcat. Java
Size: 218 bytes
How can we use Java code to obtain the string path under path,
For example, in this example,/myhibernate/src/cjq/hibernate/tutorial/EG/domesticcat. Java
Prompt for help:
public class Test { public static void main(String[] args) throws IOException { File file = new File(Test.class.getName()); System.out.println(file.getAbsolutePath()); }}
The above code can obtain the absolute path of Java, but this method is only valid when the file is a Java class.
If you want to obtain the absolute path or relative path + file name of other file types, you can do this:
First, take the project root path, then traverse the entire directory in a loop, take the file name, determine the file type, and then integrate the file path.
Public static stringbuffer sb = new stringbuffer (""); public static void main (string ARGs []) {// obtain the root path of the current project file = new file (system. getproperty ("user. dir "); file pfile = file. getparentfile (); getfilename (pfile); exportexcel (SB); // system. out. println (sb. tostring ());}
Traverse objects in the entire directory cyclically:
// Set the public static void getfilename (File file) {file [] files = file. listfiles (); For (file F: Files) {If (F! = NULL & F. isfile () {string name = f. getname (); If (name. indexof (". flowx ")! =-1) {getallfilename (f) ;}} else if (null! = F & F. isdirectory () {getfilename (f );}}}
Integration file path:
public static void getAllFileName(File file){//sb.insert(0, file.getName());if(file.getName().indexOf("src")!=-1){sb.insert(0, "/");sb.insert(0, "\n");}else{sb.insert(0, ".");sb.insert(0, file.getName());getAllFileName(file.getParentFile());}}