Get absolute path with Java programs

xiaoxiao2021-03-06  41

Before you have a procedure, I have encountered such a problem, I want to use a relative path to delete a file (actually exist), I have to delete it. It's really anxious. I finally made me a good fortune. Drop, the problem does not prevent you to talk to you, if you encounter such problems, you don't have to charge!

This is this: my Tomcat is put on the C drive, and my virtual directory is set under E: / WORK, I have a picture in E: / Work / Test / Image, Test.gif I want to pass the program Delete it, but his absolute path is uncertain (in order to take into account the transplant after the program, the absolute path is uncertain).

Suppose the del.jsp files under E: / WORK / TEST, as if you can delete it:

<% @ 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. *"%> Delete success page </ title> </ head> <body> file f = new file ("/ image /" ,test.gif ?;Boolean a = f.delete (); out.print ("a =" a); </ body> </ html></p> <p>But in fact, you will find a = false;</p> <p>This needs to get its absolute path, we use the Java program to make a special way to get JavaBean (path_test.java) that you can get absolute path.</p> <p>The code of PATH_TEST.JAVA is as follows: package pathtest; import java.io. *; import javax.servlet. *; import javax.servlet.jsp.pageContext; // Import PageContext class, don't forget public class path_test {</p> <p>Protected servletContext m_application; private bolean m_denyphysicalpath; public path_test () {</p> <p>} public final void initialize (pageContext pagecontext) throws servletexception {m_application = pageContext.getServletContext ();</p> <p>}</p> <p>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 (" // ")> = 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 ("/") 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;. elsepath = 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)."); elsereturn filePathName;} else {throw new IllegalArgumentException ( "This path does not exist (1135) ");}} if (option == 1) {if (isvirtual (path)) {path = m_Application.getRealPath (PATH);</p> <p>IF (path.endswith) Path = path filename; elsePath = String.Valueof (NEW STRINGBUFEOF (String.Valueof (Path))). Append (fileseparator); returname); return path;} (ISPHYSICAL) THROW NEW ILLEGALARGUMENTEXCEPTION ("The pathrow new illegalgumentException (" this path does not exist (1135). ");} if (option == 2) {if (isphysical) { (m_denyPhysicalPath) throw new IllegalArgumentException ( "Physical path is denied (1125)."); elsereturn filePathName; if (isVirtual (path)) throw new IllegalArgumentException ( "The path is not a physical path."); elsethrow new IllegalArgumentException ( " This path does not exist (1135). ");} Else {return null;}</p> <p>} Private boolean isVirtual (String pathName) // determines whether the virtual path {if (m_application.getRealPath (pathName)! = Null) {java.io.File virtualFile = new java.io.File (m_application.getRealPath (pathName)) Return VirtualFile.exists ();</p> <p>Else {Return False;}}</p> <p>}</p> <p>After compiling patimes_test.java, get the package Pathtest, there is a path_test.class class,</p> <p>Use the entire package to the Classes of the virtual directory, and then change the DEL.JSP file to the following procedure, everything is OK!</p> <p><! - Removed 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> Delete success page </ title> </ head> <body> <jsp: usebean id = " Pathtest "Scope =" Class = "Pathtest.Path_test" /] =TEST.INITIALIZE (PAGECONTEXT) ("/ TEST / Image /", 0) ("/ TEST / Image /", 0) ("/ TEST / Image /", 0); // Maximum parameter OUT. Print (Dir1); // Output is an absolute path file file = new file (Dir1, "Test.gif"); // Generate file objects Boolean a = file.delete (); out.print ("a =" a); </ body "> </ html> This time A = true; indicates that the deletion is successful!</p> <p>So far, the problem is all.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-77278.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="77278" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.042</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'gjbulBeCVk_2BRv4Gs7EX8LTJYZTVV7BAwvBoik64HaVLAKG5cPIZ7LXsP_2FEpEANpVclSIfv4xNljOc0_2FXUpfOJg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>