java get file path

/**
* <p>Title: main
* <p>Description: 
* @param args
*/
public static void main(String[] args) {

System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
        System.out.println(FilePath.class.getClassLoader().getResource(""));
        System.out.println(ClassLoader.getSystemResource(""));
        System.out.println(FilePath.class.getResource(""));
        System.out.println(FilePath.class.getResource("/"));//Class文件所在路径
        //System.out.println(newFile("/").getAbsolutePath());
        System.out.println(System.getProperty("user.dir"));

}


输出结果:
file:/E:/WorkSpace/4G_NGJXPT/WebRoot/WEB-INF/classes/
file:/E:/WorkSpace/4G_NGJXPT/WebRoot/WEB-INF/classes/
file:/E:/WorkSpace/4G_NGJXPT/WebRoot/WEB-INF/classes/
file:/E:/WorkSpace/4G_NGJXPT/WebRoot/WEB-INF/classes/com/wellcom/dfo/biz_modules/coa/web/
file:/E:/WorkSpace/4G_NGJXPT/WebRoot/WEB-INF/classes/
E:\WorkSpace\4G_NGJXPT


public static void main(String[] args) throws Exception {
String httpPath = "http://122.225.207.133:81/coachregister/330100/20170731/b5d371d8ca7a4cd99330efc6447b3514.jpg";
System.out.println("本地路径  " + getHttpFile(httpPath));
System.out.println("本地路径  " + getClassPath());
}


/**
* 取class本地路径
* @return 本地路径
* @throws Exception
*/
public static String getClassPath() throws Exception{
String httpPath = "C:\\Users\\well\\AppData\\Local\\Temp\\VedioCapJP.bmp";
httpPath = httpPath.replace(" \\", "/");
String localPath = PathLocate.getClassPath() + "tempFile"+ httpPath.substring(httpPath.lastIndexOf("/"));
localPath = java.net.URLDecoder.decode(localPath,"utf -8");
File files = new File(localPath);

try {
//Determine whether the directory where the target file is located exists 
        if(!files.getParentFile().exists()) { 
            //If the directory where the target file is located does not exist , then create the parent directory 
            if(!files.getParentFile().mkdirs()) {
            throw new Exception("Failed to create the directory where the temporary target file is located!");
            } 
        }
        if(!files.exists()){
            if(!files.createNewFile()){
                throw new Exception("文件不存在,创建失败!");
            }
        }
        FileInputStream fin = new FileInputStream(files);
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); 
        int sizeFile = (int) files.length();
int len = 0;
byte[] buffer = new byte[sizeFile];
while ((len = fin.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
fin.close();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

return localPath;
}



Get the path where the current file is located
File f = new File(FilePath.class.getResource("").getPath());
        System.out.println(f);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327008327&siteId=291194637