溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java文件路徑實(shí)例分析

發(fā)布時(shí)間:2022-01-12 09:25:22 來源:億速云 閱讀:158 作者:柒染 欄目:編程語言

這篇文章給大家介紹Java文件路徑實(shí)例分析,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

1. ServletFilterServlet web環(huán)境中,只要獲得javax.servlet.ServletContext類型,則可以通過 getRealPath("...") 獲得路徑。相對(duì)路徑中最頂層目錄可通過參數(shù)“"/"”獲取。

request.getSession().getServletContext().getRealPath("/");

2. JSP自定義標(biāo)簽javax.servlet.jsp.tagext.TagSupport

((javax.servlet.ServletContext)pageContext).getRealPath("");

3. 普通Java Class對(duì)象文件中使用:

ServletContext servletContext = ServletActionContext.getServletContext();

String pathName = servletContext.getRealPath("/");

this.getClass().getResource("???");

如果Class文件在頂層目錄(包)中,且“???”為空白字符串(“""”),及此方法在jar文件中執(zhí)行則會(huì)返回null。在頂層目錄(包)以下的各層目錄(包)則會(huì)返回包含協(xié)議的URL。各層文件夾(包)之間使用“/”分隔。

項(xiàng)目位置:C:project 目錄。

文件位置:C:projectTest.java

文件內(nèi)容:

/* 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文件的簡(jiǎn)單例子

// 將數(shù)據(jù)讀入字符列表data內(nèi)
char []data = new char[10240];
int num=file.read(data); 
// 將字符列表轉(zhuǎn)換成字符串 
String str=new String(data,0,num); 
// 輸出在控制臺(tái) 
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) 如何獲取當(dāng)前時(shí)間

import java.text.SimpleDateFormat;import java.util.Date;
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(today);


5) 字符或主機(jī)形式IP地址轉(zhuǎn)換為整型

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;
}

關(guān)于Java文件路徑實(shí)例分析就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI