获取当前目录/父目录的shell/Python/Java实现

假设一个工程如此安排,

project
----
    bin
    ----
      code0.sh
    src
    ----
      main
      ----
        code1
        code2
      test
      ----
        code1test
        code2test

(一) shell实现
现在code0.sh执行code1代码,shell脚本实现为(假设为python脚本):

    python $(dirname "$PWD")/src/code1.py
shell中获取当前路径为`echo "$PWD"`,
dir="$PWD"  
echo $dir
shell获取父路径为`echo $(dirname "$PWD")`
dir=$(dirname "$PWD")
echo $dir 

(二)Python实现

import os
os.getcwd()  #获取当前目录
os.path.abspath("")  #获取当前目录
os.path.abspath("..")  #获取父目录

(三)Java实现(获取工程目录后加相对目录)
package test;

import java.io.File;

public class test001 {
public static void main(String[] args) {
System.out.println(System.getProperty(“user.dir”));//user.dir指定了当前工程的路径
System.out.println(new File(“”).getAbsolutePath()); //当前工程目录
File file = new File(System.getProperty(“user.dir”)+”/src/main/java/test/test.txt”);//指定文件目录,工程目录(project+/src/main)
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
String path = Thread.currentThread().getContextClassLoader().getResource(“”).getPath();//获取编译后class文件路径。默认在target/classes
System.out.println(path);
}
}

猜你喜欢

转载自blog.csdn.net/woai8339/article/details/82016145