java代码
package com.kuang.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
web.xml中注册:
<servlet>
<servlet-name>fileservlet</servlet-name>
<servlet-class>com.kuang.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileservlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
Typora快捷整理代码“shift+tab”;
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
lastIndexOf("\\")返回"\\"的索引需要加1(lastIndexOf索引从1开始,substring索引从0开始),给substring(beginIndex ,endIndex ),获得文件名字。
beginIndex -- 起始索引(包括), 索引从 0 开始。
endIndex -- 结束索引(不包括)。
比如substring(4,10)表示取出从0开始数,索引4到索引10之间的字符串。
比如substring(4)表示取出从0开始数,索引4到结束的字符串。
例子:
public class RunoobTest {
public static void main(String args[]) {
String Str = new String("This is text");
System.out.print("返回值 :" );
System.out.println(Str.substring(4) );
System.out.print("返回值 :" );
System.out.println(Str.substring(4, 10) );
}
}
运行结果是:
返回值 : is text
返回值 : is te
lastIndexOf(String str, int fromIndex)
str:需要检索的字符串,fromIndex:索引位,lastlndexOf是反向索引。lastIndexOf(qwe,10),会返回从0到第10位最后一个qwe的索引。
lastIndexOf(String str)
str:需要检索的字符串,lastIndex(qwe),返回最后一个qwe字符串索引。
例子:
String Str = new String("菜鸟教程:www.runoob.com");
System.out.print("查找字符 o 最后出现的位置 :" );
System.out.println(Str.lastIndexOf( 'o' ));
System.out.print("从第14个位置查找字符 o 最后出现的位置 :" );
System.out.println(Str.lastIndexOf( 'o', 14 ));
运行结果:
查找字符 o 最后出现的位置 :17
从第14个位置查找字符 o 最后出现的位置 :13
转载自: https://www.cnblogs.com/zuma999/p/16618736.html