Obtain the Java file path

Source: Internet
Author: User

1. How to obtain the current file path

Frequently used:

String type: system. getproperty ("user. dir ");

Overall:

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 "));
}
}

2. Web Service

(1). WebLogic

The webapplication System File root directory is the root directory where your WebLogic installation is located.
For example, if your WebLogic is installed in C:/BEA/weblogic700 .....
Then, the root path of your file is C :/.
Therefore, you can access files on your server in two ways:
A. Use absolute path:
For example, put your parameter file in C:/yourconfig/yourconf. properties,
Use new fileinputstream ("yourconfig/yourconf. properties") directly ");
B. Use the relative path:
The root directory of the relative path is the root path of your webapplication, that is, the upper-level directory of the WEB-INF, put your parameter file in yourwebapp/yourconfig/yourconf. properties,
This method is used as follows:
New fileinputstream ("./yourconfig/yourconf. properties ");
You can select either of the two methods.

(2). Tomcat

Output System. getproperty ("user. dir") in the class; % atat_home %/bin

(3). Resin

It is not the relative path of your JSP, but the JSP Engine executes this JSP to compile it into a Servlet
For example, use the new file method to test file F = new file ("a.htm ");
This a.htm is in the resin installation directory.

(4). How to read relative paths?

In a Java file, either getresource or getresourceasstream can be used.

Example: getclass (). getresourceasstream (filepath); // filepath can be "/FILENAME", here/Represents the WEB-INF/classes under the web publishing root path

(5). Obtain the real path of the file

String file_real_path = request. getrealpath ("mypath/FILENAME ");

Request. getrealpath ("/");

3. File Operation class

Import java. Io .*;
Import java.net .*;
Import java. util .*;
// Import javax. Swing. filechooser .*;
// Import org. Jr. Swing. Filter .*;

/**
* This class encapsulates some common file operations.
* All methods are static and do not need to generate such instances,
* To avoid generating such instances, the constructor is declared as private.
* @ Since 0.1
*/

Public class fileutil {
/**
* Private constructor prevents class instantiation because the tool class does not need to be instantiated.
*/
Private fileutil (){

}

/**
* Modify the last Object Access time.
* If the file does not exist, the file is created.
* <B> at present, the behavior of this method is not stable, mainly because the method outputs some information and whether the information output is retained.

Consider. </B>
* @ Param file: the object whose last access time needs to be modified.
* @ 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 Object Access time.
* If the file does not exist, the file is created.
* <B> at present, the behavior of this method is not stable, mainly because the method outputs some information and whether the information output is retained.

Consider. </B>
* @ Param filename the name of the file whose last access time needs to be modified.
* @ Since 0.1
*/
Public static void touch (string filename ){
File file = new file (filename );
Touch (File );
}

/**
* Modify the last Object Access time.
* If the file does not exist, the file is created.
* <B> at present, the behavior of this method is not stable, mainly because the method outputs some information and whether the information output is retained.

Consider. </B>
* @ Param files the array of objects whose last access time needs to be modified.
* @ Since 0.1
*/
Public static void touch (file [] files ){
For (INT I = 0; I <files. length; I ++ ){
Touch (files );
}
}

/**
* Modify the last Object Access time.
* If the file does not exist, the file is created.
* <B> at present, the behavior of this method is not stable, mainly because the method outputs some information and whether the information output is retained.

Consider. </B>
* @ Param filenames the array of file names whose last access time needs to be modified.
* @ 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 );
}

/**
* Determine whether the specified file exists.
* @ Param filename the file name to be determined
* @ Return returns true if yes; otherwise, returns false.
* @ Since 0.1
*/
Public static Boolean isfileexist (string filename ){
Return new file (filename). isfile ();
}

/**
* Create a specified directory.
* If the parent directory of the specified directory does not exist, create all the parent directories required in the directory.
* <B> Note: Some parent directories may be created when false is returned. </B>
* @ Param file: directory to be created
* @ Return true is returned when the creation is successful. Otherwise, false is returned.
* @ Since 0.1
*/
Public static Boolean makedirectory (File file ){
File parent = file. getparentfile ();
If (parent! = NULL ){
Return parent. mkdirs ();
}
Return false;
}

/**
* Create a specified directory.
* If the parent directory of the specified directory does not exist, create all the parent directories required in the directory.
* <B> Note: Some parent directories may be created when false is returned. </B>
* @ Param filename the Directory Name of the directory to be created
* @ Return true is returned when the creation is successful. Otherwise, false is returned.
* @ Since 0.1
*/
Public static Boolean makedirectory (string filename ){
File file = new file (filename );
Return makedirectory (File );
}

/**
* Clear the files in the specified directory.
* This method will delete all files as much as possible, but if one file is not deleted, false will be returned.
* In addition, this method does not iteratively Delete sub-directories or their contents.
* @ Param directory the directory to be cleared
* @ Return returns true if all files in the directory are successfully deleted; otherwise, 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;
}

/**
* Clear the files in the specified directory.
* This method will delete all files as much as possible, but if one file is not deleted, false will be returned.
* In addition, this method does not iteratively Delete sub-directories or their contents.
* @ Param directoryname the Directory Name of the directory to be cleared
* @ Return returns true if all files in the directory are successfully deleted; otherwise, false.
* @ Since 0.1
*/
Public static Boolean emptydirectory (string directoryname ){
File dir = new file (directoryname );
Return emptydirectory (DIR );
}

/**
* Delete the specified directory and all its contents.
* @ Param dirname the Directory Name of the directory to be deleted
* @ Return true is returned when the deletion is successful. Otherwise, false is returned.
* @ Since 0.1
*/
Public static Boolean deletedirectory (string dirname ){
Return deletedirectory (new file (dirname ));
}

/**
* Delete the specified directory and all its contents.
* @ Param dir the directory to be deleted
* @ Return true is returned when the deletion is successful. Otherwise, false is returned.
* @ 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;
}

/**
* The URL of the returned file.
* @ Param File
* @ Return the URL of the file
* @ Throws malformedurlexception
* @ Since 0.4
* @ Deprecated didn't notice that the file class itself has a tourl method to convert the file path to a URL.
* Use the file. tourl method.
*/
Public static URL geturl (File file) throws malformedurlexception {
String fileurl = "file:/" + file. getabsolutepath ();
URL url = new URL (fileurl );
Return URL;
}

/**
* Get the file name from the file path.
* @ Param filepath: the file path, which can be relative or absolute.
* @ Return refers to the corresponding file name.
* @ Since 0.4
*/
Public static string getfilename (string filepath ){
File file = new file (filepath );
Return file. getname ();
}

/**
* Obtain the absolute path of the file from the file name.
* @ Param filename: File Name
* @ Return refers to the file path
* @ Since 0.4
*/
Public static string getfilepath (string filename ){
File file = new file (filename );
Return file. getabsolutepath ();
}

/**
* Convert a path in DOS/Windows format to a path in Unix/Linux format.
* In fact, it is easier to replace "/" in the path with "/", because in some cases, it is easier to convert it to this method,
* To a certain extent, "/" is more suitable for path separators than "/", and DoS/Windows also treats it as path separators.
* @ Param filepath: path before conversion
* @ Return: The converted path
* @ Since 0.4
*/
Public static string tounixpath (string filepath ){
Return filepath. Replace ('//','/');
}

/**
* Obtain the absolute path of a Unix-style file from the file name.
* @ Param filename: File Name
* @ Return refers to the Unix-style file path.
* @ Since 0.4
* @ See # tounixpath (string filepath) tounixpath
*/
Public static string getunixfilepath (string filename ){
File file = new file (filename );
Return tounixpath (file. getabsolutepath ());
}

/**
* Obtain the file type.
* It is actually the part after the last "." In the file name.
* @ Param filename: File Name
* @ Return the type part in the file name
* @ 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 );
}
}

/**
* Obtain the file type.
* It is actually the part after the last "." In the file name.
* @ Param File
* @ Return the type part in the file name
* @ Since 0.5
*/
Public static string getfiletype (File file ){
Return gettypepart (file. getname ());
}

/**
* Obtain the file name.
* It is actually the part after the last path Separator in the path.
* @ Param filename: File Name
* @ Return the name part of the file name
* @ 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 );
}
}

/**
* Obtain the parent path in the file name.
* It is valid for both path separators.
* If it does not exist, "" is returned "".
* If the file name ends with a path separator, this separator is not considered. For example, "/path/" return "".
* @ Param filename: File Name
* @ Return parent path. If the parent directory does not exist or already exists, "" is returned ""
* @ 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 );
}
}

/**
* Obtain the location where the path separator first appears in the file path.
* It Can Be A DoS or Unix-style separator.
* @ Param filename file path
* @ Return refers to the position where the path separator first appears in the path. If it does not appear,-1 is returned.
* @ Since 0.5
*/
Public static int getpathindex (string filename ){
Int point = filename. indexof ('/');
If (point =-1 ){
Point = filename. indexof ('//');
}
Return Point;
}

/**
* Obtain the location where the path separator first appears after the specified location in the file path.
* It Can Be A DoS or Unix-style separator.
* @ Param filename file path
* @ Param fromindex start to find the location
* @ Return specifies the location where the path separator appears for the first time after the specified location in the path. If it does not appear,-1 is returned.
* @ 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;
}

/**
* Obtain the last position of the path Separator in the file path.
* It Can Be A DoS or Unix-style separator.
* @ Param filename file path
* @ Return refers to the position of the path separator at the end of the path. If no separator is displayed,-1 is returned.
* @ Since 0.5
*/
Public static int getpathlsatindex (string filename ){
Int point = filename. lastindexof ('/');
If (point =-1 ){
Point = filename. lastindexof ('//');
}
Return Point;
}

/**
* Obtain the last position of the path separator before the specified position in the file path.
* It Can Be A DoS or Unix-style separator.
* @ Param filename file path
* @ Param fromindex start to find the location
* @ Return refers to the last position before the specified position in the path. If no position exists,-1 is returned.
* @ 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;
}

/**
* Remove the type part from the file name.
* @ Param filename: File Name
* @ Return the result of removing the type part
* @ Since 0.5
*/
Public static string trimtype (string filename ){
Int Index = filename. lastindexof (".");
If (index! =-1 ){
Return filename. substring (0, index );
}
Else {
Return filename;
}
}
/**
* Obtain the relative path.
* If the file name is not a sub-node of the directory name, the file name is returned.
* @ Param pathname: Directory Name
* @ Param filename: File Name
* @ Return obtain the relative path of the file name to the directory name. If the file does not exist in the directory, the file name is returned.
* @ 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. Legacy issues

Currently, new fileinputstream () only uses the absolute path, which is relatively useless, because it is more troublesome than the Web server address.

It's better to write a configuration file.

5. Read configuration files by Java file type

Configuration files are indispensable in the application system and can increase program flexibility. Java. util. properties is a class from jdk1.2 and supports the load () method until now. After jdk1.4, save (output, string)-> store (output, string ). If it is just a simple read, there is no headache at all. The web layer can use thread. currentthread (). getcontextclassloader ().
Getresourceasstream ("XX. properties"); application can be obtained directly at the classes level through new fileinputstream ("XX. properties. The key is that sometimes we need to modify the configuration file through the Web, and we cannot write the path to death. After testing, I think I have the following experiences:

1. read/write in servlet. If struts or servlet is used, you can directly configure it in the initialization parameters. When calling, you can obtain the actual path based on Servlet's getrealpath ("/"), and then use string file = This. servlet. getinitparameter ("ABC"); gets the relative path of the relative WEB-INF.
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 ();

2. Operate in JSP directly, and obtain the operable absolute address 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"); // put ABC. properties in the webroot/WEB-INF/classes/directory
Prop. Load (in );
In. Close ();

Outputstream out = new fileoutputstream (PATH); // path is the path passed in through the page
Prop. setproperty ("ABC", "abcccccc ");
Prop. Store (Out, "-test -");
Out. Close ();

3. Only use Java programs to operate resource files
Inputstream in = new fileinputstream ("ABC. properties"); // put it at the same level as classes

Outputstream out = new fileoutputstream ("ABC. properties ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.