Java如何获取当前类路径
1.如何获得当前文件路径
常用:(1).Test.class.getResource("")得到的是当前类FileTest.class文件的URI目录。不包括自己!(2).Test.class.getResource("/")得到的是当前的classpath的绝对URI路径。(3).Thread.currentThread().getContextClassLoader().getResource("")得到的也是当前ClassPath的绝对URI路径。(4).Test.class.getClassLoader().getResource("")得到的也是当前ClassPath的绝对URI路径。(5).ClassLoader.getSystemResource("")得到的也是当前ClassPath的绝对URI路径。尽量不要使用相对于System.getProperty("user.dir")当前用户目录的相对路径,后面可以看出得出结果五花八门。(6) new File("").getAbsolutePath()也可用。        2.Web服务器(1).Tomcat在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin(2).Resin不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET的路径为根.比如用新建文件法测试File f = new File("a.htm");这个a.htm在resin的安装目录下(3).如何读文件使用ServletContext.getResourceAsStream()就可以(4).获得文件真实路径String   file_real_path=ServletContext.getRealPath("mypath/filename"); 不建议使用request.getRealPath("/");3.文件操作的类,不建议使用,可以使用commons io类 

import java.io.*;
import java.net.*;
import java.util.*; /**
* 此类中封装一些常用的文件操作。
* 所有方法都是静态方法,不需要生成此类的实例,
* 为避免生成此类的实例,构造方法被申明为private类型的。
* @since 0.1
*/ public class FileUtil {
/**
* 私有构造方法,防止类的实例化,因为工具类不需要实例化。
*/
private FileUtil() { } /**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考 虑中。</b>
* @param file 需要修改最后访问时间的文件。
* @since 0.1
*/
public static void touch(File file) {
long currentTime = System.currentTimeMillis();
if (!file.exists()) {
System.err.println("file not found:" + file.getName());
System.err.println("Create a new file:" + file.getName());
try {
if (file.createNewFile()) {
// System.out.println("Succeeded!");
}
else {
// System.err.println("Create file failed!");
}
}
catch (IOException e) {
// System.err.println("Create file failed!");
e.printStackTrace();
}
}
boolean result = file.setLastModified(currentTime);
if (!result) {
// System.err.println("touch failed: " + file.getName());
}
} /**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考 虑中。</b>
* @param fileName 需要修改最后访问时间的文件的文件名。
* @since 0.1
*/
public static void touch(String fileName) {
File file = new File(fileName);
touch(file);
} /**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考 虑中。</b>
* @param files 需要修改最后访问时间的文件数组。
* @since 0.1
*/
public static void touch(File[] files) {
for (int i = 0; i < files.length; i++) {
touch(files);
}
} /**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考 虑中。</b>
* @param fileNames 需要修改最后访问时间的文件名数组。
* @since 0.1
*/
public static void touch(String[] fileNames) {
File[] files = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i++) {
files = new File(fileNames);
}
touch(files);
} /**
* 判断指定的文件是否存在。
* @param fileName 要判断的文件的文件名
* @return 存在时返回true,否则返回false。
* @since 0.1
*/
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
} /**
* 创建指定的目录。
* 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
* <b>注意:可能会在返回false的时候创建部分父目录。</b>
* @param file 要创建的目录
* @return 完全创建成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean makeDirectory(File file) {
File parent = file.getParentFile();
if (parent != null) {
return parent.mkdirs();
}
return false;
} /**
* 创建指定的目录。
* 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
* <b>注意:可能会在返回false的时候创建部分父目录。</b>
* @param fileName 要创建的目录的目录名
* @return 完全创建成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean makeDirectory(String fileName) {
File file = new File(fileName);
return makeDirectory(file);
} /**
* 清空指定目录中的文件。
* 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
* 另外这个方法不会迭代删除,即不会删除子目录及其内容。
* @param directory 要清空的目录
* @return 目录下的所有文件都被成功删除时返回true,否则返回false.
* @since 0.1
*/
public static boolean emptyDirectory(File directory) {
boolean result = false;
File[] entries = directory.listFiles();
for (int i = 0; i < entries.length; i++) {
if (!entries.delete()) {
result = false;
}
}
return true;
} /**
* 清空指定目录中的文件。
* 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
* 另外这个方法不会迭代删除,即不会删除子目录及其内容。
* @param directoryName 要清空的目录的目录名
* @return 目录下的所有文件都被成功删除时返回true,否则返回false。
* @since 0.1
*/
public static boolean emptyDirectory(String directoryName) {
File dir = new File(directoryName);
return emptyDirectory(dir);
} /**
* 删除指定目录及其中的所有内容。
* @param dirName 要删除的目录的目录名
* @return 删除成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean deleteDirectory(String dirName) {
return deleteDirectory(new File(dirName));
} /**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean deleteDirectory(File dir) {
if ( (dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " + dir +
" is not a directory. ");
} File[] entries = dir.listFiles();
int sz = entries.length; for (int i = 0; i < sz; i++) {
if (entries.isDirectory()) {
if (!deleteDirectory(entries)) {
return false;
}
}
else {
if (!entries.delete()) {
return false;
}
}
} if (!dir.delete()) {
return false;
}
return true;
} /**
* 返回文件的URL地址。
* @param file 文件
* @return 文件对应的的URL地址
* @throws MalformedURLException
* @since 0.4
* @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。
* 请使用File.toURL方法。
*/
public static URL getURL(File file) throws MalformedURLException {
String fileURL = "file:/" + file.getAbsolutePath();
URL url = new URL(fileURL);
return url;
} /**
* 从文件路径得到文件名。
* @param filePath 文件的路径,可以是相对路径也可以是绝对路径
* @return 对应的文件名
* @since 0.4
*/
public static String getFileName(String filePath) {
File file = new File(filePath);
return file.getName();
} /**
* 从文件名得到文件绝对路径。
* @param fileName 文件名
* @return 对应的文件路径
* @since 0.4
*/
public static String getFilePath(String fileName) {
File file = new File(fileName);
return file.getAbsolutePath();
} /**
* 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
* 其实就是将路径中的"/"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,
* 某中程度上说"/"比"/"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
* @param filePath 转换前的路径
* @return 转换后的路径
* @since 0.4
*/
public static String toUNIXpath(String filePath) {
return filePath.replace('//', '/');
} /**
* 从文件名得到UNIX风格的文件绝对路径。
* @param fileName 文件名
* @return 对应的UNIX风格的文件路径
* @since 0.4
* @see #toUNIXpath(String filePath) toUNIXpath
*/
public static String getUNIXfilePath(String fileName) {
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
} /**
* 得到文件的类型。
* 实际上就是得到文件名中最后一个“.”后面的部分。
* @param fileName 文件名
* @return 文件名中的类型部分
* @since 0.5
*/
public static String getTypePart(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
}
else {
return fileName.substring(point + 1, length);
}
} /**
* 得到文件的类型。
* 实际上就是得到文件名中最后一个“.”后面的部分。
* @param file 文件
* @return 文件名中的类型部分
* @since 0.5
*/
public static String getFileType(File file) {
return getTypePart(file.getName());
} /**
* 得到文件的名字部分。
* 实际上就是路径中的最后一个路径分隔符后的部分。
* @param fileName 文件名
* @return 文件名中的名字部分
* @since 0.5
*/
public static String getNamePart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return fileName;
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
if (length == 1) {
return fileName;
}
else {
return fileName.substring(0, point);
}
}
else {
return fileName.substring(secondPoint + 1, point);
}
}
else {
return fileName.substring(point + 1);
}
} /**
* 得到文件名中的父路径部分。
* 对两种路径分隔符都有效。
* 不存在时返回""。
* 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
* @param fileName 文件名
* @return 父路径,不存在或者已经是父目录时返回""
* @since 0.5
*/
public static String getPathPart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return "";
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
return "";
}
else {
return fileName.substring(0, secondPoint);
}
}
else {
return fileName.substring(0, point);
}
} /**
* 得到路径分隔符在文件路径中首次出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathIndex(String fileName) {
int point = fileName.indexOf('/');
if (point == -1) {
point = fileName.indexOf('//');
}
return point;
} /**
* 得到路径分隔符在文件路径中指定位置后首次出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @param fromIndex 开始查找的位置
* @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathIndex(String fileName, int fromIndex) {
int point = fileName.indexOf('/', fromIndex);
if (point == -1) {
point = fileName.indexOf('//', fromIndex);
}
return point;
} /**
* 得到路径分隔符在文件路径中最后出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathLsatIndex(String fileName) {
int point = fileName.lastIndexOf('/');
if (point == -1) {
point = fileName.lastIndexOf('//');
}
return point;
} /**
* 得到路径分隔符在文件路径中指定位置前最后出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @param fromIndex 开始查找的位置
* @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathLsatIndex(String fileName, int fromIndex) {
int point = fileName.lastIndexOf('/', fromIndex);
if (point == -1) {
point = fileName.lastIndexOf('//', fromIndex);
}
return point;
} /**
* 将文件名中的类型部分去掉。
* @param filename 文件名
* @return 去掉类型部分的结果
* @since 0.5
*/
public static String trimType(String filename) {
int index = filename.lastIndexOf(".");
if (index != -1) {
return filename.substring(0, index);
}
else {
return filename;
}
}
/**
* 得到相对路径。
* 文件名不是目录名的子节点时返回文件名。
* @param pathName 目录名
* @param fileName 文件名
* @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
* @since 0.5
*/
public static String getSubpath(String pathName,String fileName) {
int index = fileName.indexOf(pathName);
if (index != -1) {
return fileName.substring(index + pathName.length() + 1);
}
else {
return fileName;
}
} }

4.遗留问题目前new FileInputStream()只会使用绝对路径,相对没用过,因为要相对于web服务器地址,比较麻烦还不如写个配置文件来的快哪5.按Java文件类型分类读取配置文件配 置文件是应用系统中不可缺少的,可以增加程序的灵活性。java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) ->store(output,string)。如果只是单纯的读,根本不存在烦恼的问题。web层可以通过 Thread.currentThread().getContextClassLoader().getResourceAsStream("xx.properties") 获取;Application可以通过new FileInputStream("xx.properties");直接在classes一级获取。关键是有时我们需要通过web修改配置文件,我们不 能将路径写死了。经过测试觉得有以下心得:1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servletcontext的getRealPath("/")获取真实路径,再根据 String file = this.servlet.getInitParameter("abc");获取相对的WEB-INF的相对路径。例:InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties");Properties prop = new Properties();prop.load(input);input.close();OutputStream out = new FileOutputStream(path);prop.setProperty("abc", “test");prop.store(out, “–test–");out.close();2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。例:// jsp页面String path = pageContext.getServletContext().getRealPath("/");String realPath = path+"/WEB-INF/classes/abc.properties";//java 程序InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目录下prop.load(in);in.close();OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径prop.setProperty("abc", “abcccccc");prop.store(out, “–test–");out.close();3.只通过Java程序操作资源文件InputStream in = new FileInputStream("abc.properties"); // 放在classes同级OutputStream out = new FileOutputStream("abc.properties");=======================================<p>1、利用System.getProperty()函数获取当前路径:System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径</p><p>2、使用File提供的函数获取当前路径:File directory = new File("");//设定为当前文件夹try{    System.out.println(directory.getCanonicalPath());//获取标准的路径    System.out.println(directory.getAbsolutePath());//获取绝对路径}catch(Exceptin e){}</p><p>File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。</p><p># 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹# 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径# 至于getPath()函数,得到的只是你在new File()时设定的路径</p><p>比如当前的路径为 C:\test :File directory = new File("abc");directory.getCanonicalPath(); //得到的是C:\test\abcdirectory.getAbsolutePath();    //得到的是C:\test\abcdirecotry.getPath();                    //得到的是abc</p><p>File directory = new File(".");directory.getCanonicalPath(); //得到的是C:\testdirectory.getAbsolutePath();    //得到的是C:\test\.direcotry.getPath();                    //得到的是.</p><p>File directory = new File("..");directory.getCanonicalPath(); //得到的是C:\directory.getAbsolutePath();    //得到的是C:\test\..direcotry.getPath();                    //得到的是..</p><p> </p><p>另外:System.getProperty()中的字符串参数如下:</p><p>System.getProperty()参数大全# java.version                                Java Runtime Environment version # java.vendor                                Java Runtime Environment vendor # java.vendor.url                           Java vendor URL# java.home                                Java installation directory# java.vm.specification.version   Java Virtual Machine specification version # java.vm.specification.vendor    Java Virtual Machine specification vendor # java.vm.specification.name      Java Virtual Machine specification name# java.vm.version                        Java Virtual Machine implementation version# java.vm.vendor                        Java Virtual Machine implementation vendor# java.vm.name                        Java Virtual Machine implementation name # java.specification.version        Java Runtime Environment specification version# java.specification.vendor         Java Runtime Environment specification vendor # java.specification.name           Java Runtime Environment specification name # java.class.version                    Java class format version number# java.class.path                      Java class path# java.library.path                 List of paths to search when loading libraries# java.io.tmpdir                       Default temp file path# java.compiler                       Name of JIT compiler to use# java.ext.dirs                       Path of extension directory or directories # os.name                              Operating system name# os.arch                                  Operating system architecture# os.version                       Operating system version# file.separator                         File separator ("/" on UNIX)# path.separator                  Path separator (":" on UNIX)# line.separator                       Line separator ("\n" on UNIX)# user.name                        User's account name# user.home                              User's home directory# user.dir                               User's current working directory</p>Java如何获取当前类路径的更多相关文章
- Java中获取项目根路径和类加载路径的7种方法
		
引言 在web项目开发过程中,可能会经常遇到要获取项目根路径的情况,那接下来我就总结一下,java中获取项目根路径的7种方法,主要是通过thisClass和System,线程和request等方法. ...
 - jdbc java数据库连接 6)类路径读取——JdbcUtil的配置文件
		
之前的代码中,以下代码很多时候并不是固定的: private static String url = "jdbc:mysql://localhost:3306/day1029?useUnic ...
 - java ,js获取web工程路径
		
一.java获取web工程路径 1),在servlet可以用一下方法取得: request.getRealPath(“/”) 例如:filepach = request.getRealPath(“/” ...
 - java获取本类路径
		
(1).Test.class.getResource("") 得到的是当前类FileTest.class文件的URI目录.不包括自己! (2).Test.class.getReso ...
 - java中获取各种上下文路径的方法小结
		
一.获得都是当前运行文件在服务器上的绝对路径在servlet里用:this.getServletContext().getRealPath(); 在struts用:this.getServlet(). ...
 - 【java】获取项目资源路径
		
目资源路径分两种,一种是普通Java项目的资源路径,另一种是JavaEE项目的资源路径. 获取Java项目的包(源码下的包 或者 jar包)的资源路径 // 方法1:通过this.getClass() ...
 - java后台获取服务器相对路径,获取当前时间yyyyMMddHHmmssSSS
		
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); Date date = new Date( ...
 - Java反射特性--获取其他类实例并调用其方法
		
1. 代码结构 .├── com│ └── test│ └── MyTest.java└── MainCall.java 2. 代码内容 MyTest.java: package com.te ...
 - Java中获取路径的方法_自我分析
		
就目前的我来说最常用的两种获取路径的方法是 class.getRecource(filename) 和 class.getclassloader.getRecource(filename) 这两者的 ...
 
随机推荐
- 【转载】C#通过InsertAt方法在DataTable特定位置插入一条数据
			
在C#中的Datatable数据变量的操作过程中,可以通过DataTable变量的Rows属性的InsertAt方法往DataTable的指定位置行数位置插入一个新行数据,即往DataTable表格指 ...
 - 为元素添加 title 属性
			
---恢复内容开始--- 可以使用title属性(不要与title元素混淆)为网站上任何部分加上提示标签. ... <ul title="Table of Contents" ...
 - ubuntu升级python版本(3.5 -> 3.6)
			
#获取最新的python3.6,将其添加至当前apt库中,并自动导入公钥 $ sudo add-apt-repository ppa:jonathonf/python-3.6 $ sudo apt-g ...
 - caffe库源码剖析——net层
			
net层的功能实现主要涉及到net.hpp和net.cpp文件,让我们要捋顺它是干了什么,是如何实现的. 1. net层使用到的参数 第一步要做的事,就是查看caffe.proto文件,弄清楚net都 ...
 - JS判断是否是数组的四种做法(转载)
			
转载来源 https://www.cnblogs.com/echolun/p/10287616.html 一.前言 如何判断一个对象或一个值是否是一个数组,在面试或工作中我们常常会遇到这个问题,既然出 ...
 - 利用 AWS DMS 在线迁移 MongoDB 到 Amazon Aurora
			
将数据从一种数据库迁移到另一种数据库通常都非常具有挑战性,特别是考虑到数据一致性.应用停机时间.以及源和目标数据库在设计上的差异性等因素.这个过程中,运维人员通常都希望借助于专门的数据迁移(复制)工具 ...
 - Docker 0x13: Docker 构建集群/服务/Compose/分布式服务栈
			
目录 Docker 构建集群/服务/Compose/分布式服务栈 集群 初始化集群服务 安装docker-machine 管理节点和工作节点 docker集群构建完成 集群中部署应用 集群服务访问特性 ...
 - Httpd服务入门知识-Httpd服务常见配置案例之DSO( Dynamic Shared Object)加载动态模块配置
			
Httpd服务入门知识-Httpd服务常见配置案例之DSO( Dynamic Shared Object)加载动态模块配置 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.加载动 ...
 - BZOJ-1042:硬币购物(背包+容斥)
			
题意:硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买si的价值的东西.请问每次有多少种付款方法. 思路:这么老的题,居然今天才做到. ...
 - 实时查看mysql当前连接数
			
如何实时查看mysql当前连接数? 1.查看当前所有连接的详细资料:./mysqladmin -uadmin -p -h10.140.1.1 processlist 2.只查看当前连接数(Thread ...