substring(filePath.lastIndexOf("/")+1)
时间: 2024-04-29 10:19:26 浏览: 16
这是一个字符串处理的代码片段,它的作用是获取一个文件路径中的文件名。该代码片段使用了substring方法,它的参数是文件路径中最后一个斜杠(/)的位置加1,这样就可以截取文件路径中最后一个斜杠后面的字符串,也就是文件名。例如,如果文件路径为"/home/user/documents/file.txt",则该代码片段将返回"file.txt"。
相关问题
某产品为了防止跨目录使用了如下的代码处理路径: public static String getFileName(String filePath) { String fileName = ""; String separator = "/"; if(filePath.lastIndexOf("\\")>0){ separator = "\\"; } else{ separator = "/"; } fileName = filePath.substring(filePath.lastIndexOf(separator)+1); return fileName; } 以下哪种方法可以绕过该判断从而达到跨目录的结果? ../../../fileName ..\..\..\fileName ../../..\..\fileName ..\..\../../fileName
该方法使用了一个判断,如果路径中包含"\"则将路径分隔符设为"\",否则使用"/"作为分隔符。因此,可以绕过该判断的方法是使用一个既包含"\"又包含"/"的路径,例如使用"../../"来切换目录,但是不能通过任意输入字符串来实现跨目录,要根据实际情况来进行构造。因此,以下任何一种方法都不一定可以绕过该判断,需要具体情况具体分析。
Part part=request.getPart("companyPic"); String fileName=part.getSubmittedFileName(); String newFileName=System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf(".")); String filepath =getServletContext().getRealPath("/"); filepath=filepath.substring(0,filepath.indexOf(getServletContext().getServletContextName())); filepath=filepath+"upload/companyPic"; getServletContext().log("上传路径为:"+filepath) ; File f=new File(filepath); if(!f.exists()) f.mkdirs(); part.write(filepath+"/"+newFileName);如何更改上传地址
要更改上传地址,需要更改以下代码中的"upload/companyPic"部分:
filepath = getServletContext().getRealPath("/");
filepath = filepath.substring(0, filepath.indexOf(getServletContext().getServletContextName()));
filepath = filepath + "upload/companyPic";
您可以将“upload/companyPic”更改为新的上传路径,然后保存并重新运行代码即可。请确保新路径存在并具有正确的权限。