Obtain the absolute path using a Java program

Source: Internet
Author: User
When I was a program in the previous section, I encountered such a problem. I wanted to use the relative path to delete a file (actually exists), but I couldn't delete it all the time. it's really anxious. I finally spent a lot of effort to solve the problem. Let's talk about it without defense. In case of such a problem, you don't have to work hard!

The situation is as follows: My Tomcat is installed on the C drive, and my virtual directory is located under E:/work: there is an image under/work/test/image. test.gif I want to delete it through the program, but his absolute path is uncertain (in order to take into account the future transplantation of the program, the absolute path is uncertain ).

Assume that the del. jsp file is in e:/work/test and can be deleted using the following program:

<! -- Original del. jsp source file -->
<% @ Page contentType = "text/html; charset = GBK" errorPage = "" %>
<% Request. setCharacterEncoding ("GBK"); %>
<% @ Page language = "java" import = "java. SQL. * "import =" java. util. * "import =" java. text. * "import =" java. io. * "%>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
<Title> deletion successful page </title>
</Head>
<Body>
File f = new File ("/image/", test.gif );
Boolean a = f. delete ();
Out. print ("a =" + );
</Body>
</Html>

But in fact it doesn't work. You will find a = false;

In this case, we need to obtain the absolute path. We can use the java program to create a javaBean (path_test.java) dedicated to obtain the absolute path.

The code for path_test.java is as follows:
Package pathtest;
Import java. io .*;
Import javax. servlet .*;
Import javax. servlet. jsp. PageContext; // import the PageContext class. Do not forget it.
Public class path_test
{

Protected ServletContext m_application;
Private boolean m_denyPhysicalPath;
Public path_test ()
{

}
Public final void initialize (PageContext pageContext)
Throws ServletException
{
M_application = pageContext. getServletContext ();

}

Public String getPhysicalPath (String filePathName, int option)
Throws IOException
{
String path = new String ();
String fileName = new String ();
String fileSeparator = new String ();
Boolean isPhysical = false;
FileSeparator = System. getProperty ("file. separator ");
If (filePathName = null)
Throw new IllegalArgumentException ("There is no specified destination file (1140 ).");
If (filePathName. equals (""))
Throw new IllegalArgumentException ("There is no specified destination file (1140 ).");
If (filePathName. lastIndexOf ("//")> = 0)
{
Path = filePathName. substring (0, filePathName. lastIndexOf ("//"));
FileName = filePathName. substring (filePathName. lastIndexOf ("//") + 1 );
}
If (filePathName. lastIndexOf ("/")> = 0)
{
Path = filePathName. substring (0, filePathName. lastIndexOf ("/"));
FileName = filePathName. substring (filePathName. lastIndexOf ("/") + 1 );
}
Path = path. length ()! = 0? Path :"/";
Java. io. File physicalPath = new java. io. File (path );
If (physicalPath. exists ())
IsPhysical = true;
If (option = 0)
{
If (isVirtual (path ))
{
Path = m_application.getRealPath (path );
If (path. endsWith (fileSeparator ))
Path = path + fileName;
Else
Path = String. valueOf (new StringBuffer (String. valueOf (path). append (fileSeparator). append (fileName ));
Return path;
}
If (isPhysical)
{
If (m_denyPhysicalPath)
Throw new illegalargumentexception ("physical path is denied (1125 ).");
Else
Return filepathname;
} Else
{
Throw new illegalargumentexception ("this path does not exist (1135 ).");
}
}
If (option = 1)
{
If (isvirtual (PATH ))
{
Path = m_application.getrealpath (PATH );
If (path. endswith (fileseparator ))
Path = path + filename;
Else
Path = string. valueof (New stringbuffer (string. valueof (PATH). append (fileseparator). append (filename ));
Return path;
}
If (isphysical)
Throw new illegalargumentexception ("the path is not a virtual path .");
Else
Throw new illegalargumentexception ("this path does not exist (1135 ).");
}
If (option = 2)
{
If (isPhysical)
If (m_denyPhysicalPath)
Throw new IllegalArgumentException ("Physical path is denied (1125 ).");
Else
Return filePathName;
If (isVirtual (path ))
Throw new IllegalArgumentException ("The path is not a physical path .");
Else
Throw new IllegalArgumentException ("This path does not exist (1135 ).");
}

Else
{
Return null;
}

}
Private boolean isVirtual (String pathName) // determines whether it is a virtual path.
{
If (m_application.getRealPath (pathName )! = Null)
{
Java. io. File virtualFile = new java. io. File (m_application.getRealPath (pathName ));
Return virtualFile. exists ();
}

Else
{
Return false;
}
}

}

After compiling path_test.java, get the package pathtest, which contains the path_test.class class,

Put the entire package under the classes of the virtual directory, and then change the del. jsp file to the following program. Everything is OK!

<! -- Modified del. jsp source file -->
<% @ Page contentType = "text/html; charset = GBK" errorPage = "" %>
<% Request. setCharacterEncoding ("GBK"); %>
<% @ Page language = "java" import = "java. SQL. * "import =" java. util. * "import =" java. text. * "import =" java. io. * "%>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
<Title> deletion successful page </title>
</Head>
<Body>
<Jsp: useBean id = "pathtest" scope = "page" class = "pathtest. path_test"/>
Pathtest. initialize (pageContext); // Initialization
String dir1 = pathtest. getPhysicalPath ("/test/image/", 0); // pass the Parameter
Out. print (dir1); // The output path is absolute.
File file = new File (dir1, "test.gif"); // generate a File object
Boolean a = file. delete ();
Out. print ("a =" + );
</Body ">
</Html>

At this time, a = true; indicates that the deletion is successful!

So far, all problems have been solved.

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.