Get the current java file path + file full name

In development tools, such as a file name for the java Cat.java

At this time of Cat.java right click -> Properties -> Resources option, 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 now java code, get that string Path string path under it,

As in the present embodiment is: /MyHibernate/src/cjq/hibernate/tutorial/eg/DomesticCat.java

Help users suggests:

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 codes can be obtained absolute path of the java, but this method only when the java class file is valid.

If you want to get the absolute path of the other file types or relative path + file name, you can be:

First take root project, and then loop through the entire directory of files, take the file name to determine the file type, and then integrate the file path.

public static StringBuffer sb = new StringBuffer("");
	public static void main(String args[]){	
		//获得当前项目的根路径
		File file = new File(System.getProperty("user.dir"));
		File pfile = file.getParentFile();
		getFileName(pfile);
		exportExcel(sb);
		//System.out.println(sb.toString());
	}

Loop through the entire directory of files:

//设置指定文件类型的文件路径
	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());
		}
	}




 

 

Reproduced in: https: //my.oschina.net/u/2552902/blog/543820

Guess you like

Origin blog.csdn.net/weixin_33895475/article/details/92327005