Author: Wangqui Welcome to visit my website: www.marksaas.com
Yesterday saw an article is about resin classloader to get the absolute path of the project, the original link: http://coolshell.cn/articles/6112.html
I just want to try it under Tomcat, the result is a null pointer error, D:\Tomcat%206\webapps\cloud\WEB-INF\classes\b.txt (the system cannot find the specified path.) )
Let me start with the questions and test code for the original article.
The idea of the original article author is to define a servlet and then invoke the GetPath method of the path class in the servlet, GetPath method returns the absolute path of the engineering classpath, displayed in the JSP. In the path class, the A.txt file in the current project Classpath path is read through the getresourceasstream of the class and written to B.txt under the GetResource path. The test code is as follows: Path.java
public class Path {public
String GetPath () throws IOException
{
InputStream is = This.getclass (). getResourceAsStream ("/a.txt");
File File = new file (Path.class.getResource ("/"). GetPath () + "/b.txt");
OutputStream OS = new FileOutputStream (file);
int bytesread = 0;
byte[] buffer = new byte[8192];
while ((bytesread = is.read (buffer, 0, 8192))!=-1) {
os.write (buffer, 0, bytesread);
}
Os.close ();
Is.close ();
Return This.getclass (). GetResource ("/"). GetPath ();
}
Pathservlet.java
public class Pathservlet extends HttpServlet {private static final long Serialversionuid = 44436558
31011903288L;
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException
{Path PATH = new Path ();
Request.setattribute ("Path", Path.getpath ());
PrintWriter out = Response.getwriter ();
Out.println ("Class.getResource ('/"). GetPath (): "+ Path.getpath ()); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex
ception {doget (request, response); }
}
For my test results, my post error is D:\Tomcat%206\webapps\cloud\WEB-INF\classes\b.txt (the system cannot find the specified path.) It is obvious that the b.txt is an error, and we are using the file File=new file (Path.class.getResource ("/"). GetPath () + "/b.txt"); Read B.tex, reading the structure read d:\ Tomcat%206\webapps\cloud\web-inf\classes\b.txt on, the correct path should be D:\Tomcat\webapps\cloud\WEB-INF\classes\b.txt, do not know how to add% 206 characters, I then check on the Internet, find the current class with the class loader seems to use what agent what, I also a little dizzy, have know the children's shoes welcome to explore. Later in the Web environment or using a servlet to get the project path is better, do not use the current class to get, it is likely to be a variety of inexplicable problems.