Java路径,文件等

1. ServletFilterServlet 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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值