1. 在ServletFilter等Servlet web环境中,只要获得javax.servlet.ServletContext类型,则可以通过 getRealPath("...") 获得路径。相对路径中最顶层目录可通过参数“"/"”获取。
request.getSession().getServletContext().getRealPath("/");
2. JSP自定义标签javax.servlet.jsp.tagext.TagSupport
((javax.servlet.ServletContext)pageContext).getRealPath("");
3. 普通Java Class对象文件中使用:
ServletContext servletContext = ServletActionContext.getServletContext();
String pathName = servletContext.getRealPath("/");
this.getClass().getResource("???");
如果Class文件在顶层目录(包)中,且“???”为空白字符串(“""”),及此方法在jar文件中执行则会返回null。在顶层目录(包)以下的各层目录(包)则会返回包含协议的URL。各层文件夹(包)之间使用“/”分隔。
项目位置:C:project 目录。
文件位置:C:projectTest.java
文件内容:
/* source begin. */
public class Test {
public Test () {
System.out.println(this.getClass().getResource(""));
System.out.println(this.getClass().getResource("."));
System.out.println(this.getClass().getResource("/"));
System.out.println(this.getClass().getResource("Test.class"));
}
4)
ServletActionContext.getRequest().getContextPath();
取得Tomcat中配置好的路径名称。
2) 读取JAVA文件的简单例子
// 将数据读入字符列表data内
char []data = new char[10240];
int num=file.read(data);
// 将字符列表转换成字符串
String str=new String(data,0,num);
// 输出在控制台
System.out.println("Characters read= "+num);
System.out.println(str);
file.close();
3) Hash MAP的遍历
Map re
…
Iterator it = ret.keySet().iterator();
while( it.hasNext() )
{
String key = it.next();
String value = ret.get(key).toString();
System.out.println("Key:" + key );
System.out.println("Value:" + value );
}
4) 如何获取当前时间
import java.text.SimpleDateFormat;
import java.util.Date;
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(today);
5) 字符或主机形式IP地址转换为整型
public static int inet_addr(String src)
throws UnknownHostException
{
InetAddress address = InetAddress.getByName(src);
int numeric_ip = 0;
byte [] buf = address.getAddress();
if((buf != null)&&(buf.length == 4)) {
numeric_ip = buf[3] & 0xFF;
numeric_ip |= ((buf[2] << 8) & 0xFF00);
numeric_ip |= ((buf[1] << 16) & 0xFF0000);
numeric_ip |= ((buf[0] << 24) & 0xFF000000);
}
return numeric_ip;
}
[@more@]来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9402971/viewspace-1021571/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/9402971/viewspace-1021571/