java获取文件路径

阅读更多
/**
*

Title: main
*

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 {
//判断目标文件所在的目录是否存在 
        if(!files.getParentFile().exists()) { 
            //如果目标文件所在的目录不存在,则创建父目录 
            if(!files.getParentFile().mkdirs()) {
            throw new Exception("创建临时目标文件所在目录失败!");
            } 
        }
        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;
}



获取当前文件所在的路径
File f = new File(FilePath.class.getResource("").getPath());
        System.out.println(f);

你可能感兴趣的:(java)