Get absolute path with Java programs

xiaoxiao2021-03-06  48

Use the Java program to get a procedure before the absolute path, encounter such a problem, want to use a relative path to delete a file (actually exist), always delete. It's really anxious, and finally let me spend a big The strength is to solve it, the problem does not prevent you to talk to you, if you encounter such problems, you don't have to charge again! 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: <% @ 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> But in fact, you will find A = false; this will take its absolute path, we use the Java program to make a special path JavaBean (path_test.java) Yes.</p> <p>path_test.java code is as follows: package pathtest; import java.io *; import javax.servlet *; import javax.servlet.jsp.PageContext; // import PageContext class, do not forget 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 (")) "))" "There IS No Specified Destination File (1140)); if (filepathname.lastindexof (" // ")> = 0) {path = filepathname.substring (0, filepathname.lastindexof ("//")); filename = filepathname.substring (Fil EpathName.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 =</p> <p>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). ");}} F (option == 1) {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) );} IF (isphysical) Throw new IllegalargumentException ("THIS NOT A Virtual Path."); Elsethrow New IllegaLutException ("this path does not exist (1135).");} if (option == 2 ) {if (isPhysical) if (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 IllegalarGumeTexcep TION ("This path does not exist (1135).");} else {return null;}}} private bolean isvirtual (string pathname) // Detailed whether it is a virtual path {if (m_application.getRealPath (Pathname)! = null) {java.io.file VirtualFile = new java.io.file (m_application.getRealPath (Pathname)); returnifile.exists ();} else {return false;}}} After compiling Path_Test.java, get Pathtest, There is a PATH_TEST.CLASS class, put the entire package to the Classes of the virtual directory, and then change the DEL.JSP file to the following procedure, everything is OK! <! - Removed DEL.JSP source file -> <% @ page contenttype = "text / html; charset = GBK" errorpage = ""%> <% request.setcharacterencoding ("gbk");%> <% @</p> <p>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 = "pattest" Scope = "Page" Class = "Pathtest.path_test" / Jinpathtest.initialize (PageContext );// Initialization String Dir1 = Pathtest.getPhysicalPath ("/ TEST / Image /", 0); // Maximum parameter OUT.PRINT (Dir1 ); // Output is the 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! So, the problem is all done. Source: Hou Guang New Date: 2004-10-29</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-79548.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="79548" 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.033</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 = 'vhyfih5mzGExALmJqU1BwhzXyb0Z9tWlb7PFdH5I53dQVHoG1m7j6_2FkSOVUY5R4HV2QCL7HVr_2Fm4n8PUrzR4yA_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>