温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java文件路径实例分析

发布时间:2022-01-12 09:25:22 来源:亿速云 阅读:146 作者:柒染 栏目:编程语言

这篇文章给大家介绍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) <%=request.getcontextpath()%>
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的遍历

Mapre
…
Iteratorit = 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);
} 
returnnumeric_ip;
}

关于Java文件路径实例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI