In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how Java gets the current file path". In daily operation, I believe many people have doubts about how Java gets the current file path. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the question of "how to get the current file path by Java". Next, please follow the editor to study!
1. How to get the current file path
Commonly used:
String type: System.getProperty ("user.dir")
Comprehensive:
Package com.zcjl.test.base
Import java.io.File
Public class Test {
Public static void main (String [] args) throws Exception {
System.out.println (Thread.currentThread (). GetContextClassLoader (). GetResource ("))
System.out.println (Test.class.getClassLoader () .getResource ("))
System.out.println (ClassLoader.getSystemResource ("))
System.out.println (Test.class.getResource ("))
System.out.println (Test.class.getResource (/))
System.out.println (new File ("). GetAbsolutePath ())
System.out.println (System.getProperty ("user.dir"))
}
}
[@ more@]
In 2.Web service
(1) Weblogic
WebApplication's system file root directory is the root directory where your weblogic installation is located.
For example, if your weblogic is installed on c:beaweblogic700.
So, your file root path is cvv.
So, there are two ways to access your server-side files:
a. Use absolute paths:
For example, put your parameter file in c:yourconfigyourconf.properties
Use new FileInputStream directly ("yourconfig/yourconf.properties")
b. Use relative paths:
The root directory of the relative path is the root path of your webapplication, that is, the directory above WEB-INF. Put your parameter files in yourwebappyourconfigyourconf.properties.
Use as follows:
New FileInputStream (". / yourconfig/yourconf.properties")
You can choose either of these ways.
(2) Tomcat
Output System.getProperty ("user.dir") in the class; shows Tomcat_Home%/bin
(3) Resin
It's not the relative path that your JSP puts, it's the JSP engine that executes the JSP to compile into SERVLET.
The path is the root. For example, use the new file method to test File f = new File ("a.htm")
This a.htm is in the installation directory of resin
(4)。 How to read the relative path?
Either getResource or getResourceAsStream can be found in the Java file
Example: getClass () .getResourceAsStream (filePath); / / filePath can be "/ filename", where / represents WEB-INF/classes under the root path of web publication
(5)。 Get the real path of the file
String file_real_path=request.getRealPath ("mypath/filename")
Usually use request.getRealPath ("/")
3. Classes for file operations
Import java.io.*
Import java.net.*
Import java.util.*
/ / import javax.swing.filechooser.*
/ / import org.jr.swing.filter.*
/ * *
* some common file operations are encapsulated in this class.
* all methods are static, and there is no need to generate instances of this class
* to avoid generating an instance of this class, the constructor is declared to be of type private.
* @ since 0.1
, /
Public class FileUtil {
/ * *
* Private constructors to prevent class instantiation, because utility classes do not need to be instantiated.
, /
Private FileUtil () {
}
/ * *
* modify the last access time of the file.
* create a file if it does not exist.
* at present, the behavior of this method is not stable, mainly because the method has some information output, and whether the information output is retained or not is still under examination.
I'm worried.
* @ param file needs to modify the file of the last access time.
* @ 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 ())
}
}
/ * *
* modify the last access time of the file.
* create a file if it does not exist.
* at present, the behavior of this method is not stable, mainly because the method has some information output, and whether the information output is retained or not is still under examination.
I'm worried.
* @ param fileName needs to modify the file name of the last access time.
* @ since 0.1
, /
Public static void touch (String fileName) {
File file = new File (fileName)
Touch (file)
}
/ * *
* modify the last access time of the file.
* create a file if it does not exist.
* at present, the behavior of this method is not stable, mainly because the method has some information output, and whether the information output is retained or not is still under examination.
I'm worried.
* @ param files needs to modify the file array of the last access time.
* @ since 0.1
, /
Public static void touch (File [] files) {
For (int I = 0; I
< files.length; i++) { touch(files); } } /** * 修改文件的最后访问时间。 * 如果文件不存在则创建该文件。 * 目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考 虑中。 * @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(); } /** * 创建指定的目录。 * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 * 注意:可能会在返回false的时候创建部分父目录。 * @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; } /** * 创建指定的目录。 * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 * 注意:可能会在返回false的时候创建部分父目录。 * @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). If you just read it, there will be no trouble at all. The web layer is available through Thread.currentThread (). GetContextClassLoader ().
GetResourceAsStream ("xx.properties"); Application can be obtained through new FileInputStream ("xx.properties"); directly at the classes level. The point is that sometimes we need to modify the configuration file through web, and we can't write the path to death. After testing, I feel that I have the following experience:
Read and write in 1.servlet. If you use Struts or Servlet, you can configure it directly in the initialization parameters. When calling, you can get the real path according to the getRealPath ("/") of servlet, and then get the relative path of the relative WEB-INF according to String file = this.servlet.getInitParameter ("abc").
Example:
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 ()
two。 Operate directly in jsp and obtain the absolute address that can be operated through the jsp built-in object.
Example:
/ / jsp page
String path = pageContext.getServletContext () .getRealPath ("/")
String realPath = path+ "/ WEB-INF/classes/abc.properties"
/ / java program
InputStream in = getClass () .getClassLoader () .getResourceAsStream ("abc.properties"); / / abc.properties is placed in the webroot/WEB-INF/classes/ directory
Prop.load (in)
In.close ()
OutputStream out = new FileOutputStream (path); / / path is the path passed through the page
Prop.setProperty ("abc", "abcccccc")
Prop.store (out, "- test-")
Out.close ()
3. Manipulate resource files only through Java programs
InputStream in = new FileInputStream ("abc.properties"); / / put at the same level as classes
OutputStream out = new FileOutputStream ("abc.properties")
At this point, the study on "how to get the current file path by Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.