導航:首頁 > 編程語言 > java讀取工程文件

java讀取工程文件

發布時間:2022-08-10 17:02:15

java怎麼讀取java工程的文件

平時寫程序的時候,很多時候提示文件找不到,而拋出了異常,現在整理如下

一 相對路徑的獲得
說明:相對路徑(即不寫明時候到底相對誰)均可通過以下方式獲得(不論是一般的java項目還是web項目)
String relativelyPath=System.getProperty("user.dir");
上述相對路徑中,java項目中的文件是相對於項目的根目錄
web項目中的文件路徑視不同的web伺服器不同而不同(tomcat是相對於 tomcat安裝目錄\bin)

二 類載入目錄的獲得(即當運行時某一類時獲得其裝載目錄)
1.1)通用的方法一(不論是一般的java項目還是web項目,先定位到能看到包路徑的第一級目錄)

InputStream is=TestAction.class.getClassLoader().getResourceAsStream("test.txt");
(test.txt文件的路徑為 項目名\src\test.txt;類TestAction所在包的第一級目錄位於src目錄下)

上式中將TestAction,test.txt替換成對應成相應的類名和文件名字即可

1.2)通用方法二 (此方法和1.1中的方法類似,不同的是此方法必須以'/'開頭,
InputStream is=Test1.class.getResourceAsStream("/test.txt");
(test.txt文件的路徑為 項目名\src\test.txt,類Test1所在包的第一級目錄位於src目錄下)

三 web項目根目錄的獲得(發布之後)
1 從servlet出發

可建立一個servlet在其的init方法中寫入如下語句
ServletContext s1=this.getServletContext();
String temp=s1.getRealPath("/"); (關鍵)
結果形如:D:\工具\Tomcat-6.0\webapps\002_ext\ (002_ext為項目名字)

如果是調用了s1.getRealPath("")則輸出D:\工具\Tomcat-6.0\webapps\002_ext(少了一個"\")
2 從httpServletRequest出發

String cp11111=request.getSession().getServletContext().getRealPath("/");

結果形如:D:\工具\Tomcat-6.0\webapps\002_ext\

四 classpath的獲取(在Eclipse中為獲得src或者classes目錄的路徑)
方法一 Thread.currentThread().getContextClassLoader().getResource("").getPath()
eg: String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("t---"+t);
輸出:t---/E:/order/002_ext/WebRoot/WEB-INF/classes/

方法二 JdomParse.class.getClassLoader().getResource("").getPath() (JdomParse為src某一個包中的類,下同)

② java怎麼讀取同一個工程裡面的src目錄下的文件

在java中獲得文件的路徑在我們做上傳文件操作時是不可避免的。

web 上運行
1:this.getClass().getClassLoader().getResource("/").getPath();
this.getClass().getClassLoader().getResource("").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
System.getProperty("user.dir");
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 項目的絕對路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

2:this.getClass().getResource("/").getPath();
this.getClass().getResource("").getPath(); 得到的是當前類 文件的URI目錄。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/com/jebel/helper/
this.getClass().getResource(".").getPath(); X 不 能運行

3:Thread.currentThread().getContextClassLoader().getResource("/").getPath()
Thread.currentThread().getContextClassLoader().getResource("").getPath() 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
Thread.currentThread().getContextClassLoader().getResource(".").getPath() 得到的是 項目的絕對路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

在本地運行中
1:this.getClass().getClassLoader().getResource("").getPath();
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes
this.getClass().getClassLoader().getResource(".").getPath(); X 不 能運行
2:this.getClass().getResource("").getPath();
this.getClass().getResource(".").getPath(); 得到的是當前類 文件的URI目錄。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes/com/jebel/helper/
/D:/myProjects/hp/WebRoot/WEB-INF/classes/ 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes

③ java程序讀取資源文件時路徑如何指定

(1)、request.getRealPath("/");//不推薦使用獲取工程的根路徑
(2)、request.getRealPath(request.getRequestURI());//獲取jsp的路徑,這個方法比較好用,可以直接在servlet和jsp中使用
(3)、request.getSession().getServletContext().getRealPath("/");//獲取工程的根路徑,這個方法比較好用,可以直接在servlet和jsp中使用
(4)、 this.getClass().getClassLoader().getResource("").getPath();//獲取工程classes 下的路徑,這個方法可以在任意jsp,servlet,java文件中使用,因為不管是jsp,servlet其實都是java程序,都是一個 class。所以它應該是一個通用的方法。
0、關於絕對路徑和相對路徑
1.基本概念的理解絕對路徑:絕對路徑就是你的主頁上的文件或目錄在硬碟上真正的路徑,(URL和物理路徑)例 如:C:xyz est.txt 代表了test.txt文件的絕對路徑。http://www.sun.com/index.htm也代表了一個URL絕對路徑。相對路徑:相對與某個基 准目錄的路徑。包含Web的相對路徑(HTML中的相對目錄),例如:在Servlet中,"/"代表Web應用的跟目錄。和物理路徑的相對表示。例 如:"./" 代表當前目錄,"../"代表上級目錄。這種類似的表示,也是屬於相對路徑。另外關於URI,URL,URN等內容,請參考RFC相關文檔標准。RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,(http://www.ietf.org/rfc/rfc2396.txt)2.關於JSP/Servlet中的相對路徑和絕對路徑。 2.1伺服器端的地址伺服器端的相對地址指的是相對於你的web應用的地址,這個地址是在伺服器端解析的(不同於html和javascript中的相對 地址,他們是由客戶端瀏覽器解析的)
1、request.getRealPath
方法:request.getRealPath("/")
得到的路徑:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\
方法:request.getRealPath(".")
得到的路徑:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\.
方法:request.getRealPath("")
得到的路徑:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest
request.getRealPath("web.xml")
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\web.xml
2、request.getParameter("");
ActionForm.getMyFile();
方法:String filepath = request.getParameter("myFile");
得到的路徑:D:\VSS安裝目錄\users.txt
方法:String filepath = ActionForm.getMyFile();
得到的路徑:D:\VSS安裝目錄\users.txt
--------------------------------------------------
strutsTest 為工程名
myFile 在ActionForm中,為private String myFile;
在jsp頁面中:為<html:file property="myFile"></html:file>

④ java文件如何讀取

java讀取文件方法大全
一、多種方式讀文件內容。

1、按位元組讀取文件內容
2、按字元讀取文件內容
3、按行讀取文件內容
4、隨機讀取文件內容
Java代碼
1. import java.io.BufferedReader;
2. import java.io.File;
3. import java.io.FileInputStream;
4. import java.io.FileReader;
5. import java.io.IOException;
6. import java.io.InputStream;
7. import java.io.InputStreamReader;
8. import java.io.RandomAccessFile;
9. import java.io.Reader;
10.
11. public class ReadFromFile {
12. /**
13. * 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
14. *
15. * @param fileName
16. * 文件的名
17. */
18. public static void readFileByBytes(String fileName) {
19. File file = new File(fileName);
20. InputStream in = null;
21. try {
22. System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
23. // 一次讀一個位元組
24. in = new FileInputStream(file);
25. int tempbyte;
26. while ((tempbyte = in.read()) != -1) {
27. System.out.write(tempbyte);
28. }
29. in.close();
30. } catch (IOException e) {
31. e.printStackTrace();
32. return;
33. }
34. try {
35. System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
36. // 一次讀多個位元組
37. byte[] tempbytes = new byte[100];
38. int byteread = 0;
39. in = new FileInputStream(fileName);
40. ReadFromFile.showAvailableBytes(in);
41. // 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
42. while ((byteread = in.read(tempbytes)) != -1) {
43. System.out.write(tempbytes, 0, byteread);
44. }
45. } catch (Exception e1) {
46. e1.printStackTrace();
47. } finally {
48. if (in != null) {
49. try {
50. in.close();
51. } catch (IOException e1) {
52. }
53. }
54. }
55. }
56.
57. /**
58. * 以字元為單位讀取文件,常用於讀文本,數字等類型的文件
59. *
60. * @param fileName
61. * 文件名
62. */
63. public static void readFileByChars(String fileName) {
64. File file = new File(fileName);
65. Reader reader = null;
66. try {
67. System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
68. // 一次讀一個字元
69. reader = new InputStreamReader(new FileInputStream(file));
70. int tempchar;
71. while ((tempchar = reader.read()) != -1) {
72. // 對於windows下,\r\n這兩個字元在一起時,表示一個換行。
73. // 但如果這兩個字元分開顯示時,會換兩次行。
74. // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
75. if (((char) tempchar) != '\r') {
76. System.out.print((char) tempchar);
77. }
78. }
79. reader.close();
80. } catch (Exception e) {
81. e.printStackTrace();
82. }
83. try {
84. System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
85. // 一次讀多個字元
86. char[] tempchars = new char[30];
87. int charread = 0;
88. reader = new InputStreamReader(new FileInputStream(fileName));
89. // 讀入多個字元到字元數組中,charread為一次讀取字元數
90. while ((charread = reader.read(tempchars)) != -1) {
91. // 同樣屏蔽掉\r不顯示
92. if ((charread == tempchars.length)
93. && (tempchars[tempchars.length - 1] != '\r')) {
94. System.out.print(tempchars);
95. } else {
96. for (int i = 0; i < charread; i++) {
97. if (tempchars[i] == '\r') {
98. continue;
99. } else {
100. System.out.print(tempchars[i]);
101. }
102. }
103. }
104. }
105.
106. } catch (Exception e1) {
107. e1.printStackTrace();
108. } finally {
109. if (reader != null) {
110. try {
111. reader.close();
112. } catch (IOException e1) {
113. }
114. }
115. }
116. }
117.
118. /**
119. * 以行為單位讀取文件,常用於讀面向行的格式化文件
120. *
121. * @param fileName
122. * 文件名
123. */
124. public static void readFileByLines(String fileName) {
125. File file = new File(fileName);
126. BufferedReader reader = null;
127. try {
128. System.out.println("以行為單位讀取文件內容,一次讀一整行:");
129. reader = new BufferedReader(new FileReader(file));
130. String tempString = null;
131. int line = 1;
132. // 一次讀入一行,直到讀入null為文件結束
133. while ((tempString = reader.readLine()) != null) {
134. // 顯示行號
135. System.out.println("line " + line + ": " + tempString);
136. line++;
137. }
138. reader.close();
139. } catch (IOException e) {
140. e.printStackTrace();
141. } finally {
142. if (reader != null) {
143. try {
144. reader.close();
145. } catch (IOException e1) {
146. }
147. }
148. }
149. }
150.
151. /**
152. * 隨機讀取文件內容
153. *
154. * @param fileName
155. * 文件名
156. */
157. public static void readFileByRandomAccess(String fileName) {
158. RandomAccessFile randomFile = null;
159. try {
160. System.out.println("隨機讀取一段文件內容:");
161. // 打開一個隨機訪問文件流,按只讀方式
162. randomFile = new RandomAccessFile(fileName, "r");
163. // 文件長度,位元組數
164. long fileLength = randomFile.length();
165. // 讀文件的起始位置
166. int beginIndex = (fileLength > 4) ? 4 : 0;
167. // 將讀文件的開始位置移到beginIndex位置。
168. randomFile.seek(beginIndex);
169. byte[] bytes = new byte[10];
170. int byteread = 0;
171. // 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
172. // 將一次讀取的位元組數賦給byteread
173. while ((byteread = randomFile.read(bytes)) != -1) {
174. System.out.write(bytes, 0, byteread);
175. }
176. } catch (IOException e) {
177. e.printStackTrace();
178. } finally {
179. if (randomFile != null) {
180. try {
181. randomFile.close();
182. } catch (IOException e1) {
183. }
184. }
185. }
186. }
187.
188. /**
189. * 顯示輸入流中還剩的位元組數
190. *
191. * @param in
192. */
193. private static void showAvailableBytes(InputStream in) {
194. try {
195. System.out.println("當前位元組輸入流中的位元組數為:" + in.available());
196. } catch (IOException e) {
197. e.printStackTrace();
198. }
199. }
200.
201. public static void main(String[] args) {
202. String fileName = "C:/temp/newTemp.txt";
203. ReadFromFile.readFileByBytes(fileName);
204. ReadFromFile.readFileByChars(fileName);
205. ReadFromFile.readFileByLines(fileName);
206. ReadFromFile.readFileByRandomAccess(fileName);
207. }
208. }

二、將內容追加到文件尾部
1. import java.io.FileWriter;
2. import java.io.IOException;
3. import java.io.RandomAccessFile;
4.
5. /**
6. * 將內容追加到文件尾部
7. */
8. public class AppendToFile {
9.
10. /**
11. * A方法追加文件:使用RandomAccessFile
12. * @param fileName 文件名
13. * @param content 追加的內容
14. */
15. public static void appendMethodA(String fileName, String content) {
16. try {
17. // 打開一個隨機訪問文件流,按讀寫方式
18. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
19. // 文件長度,位元組數
20. long fileLength = randomFile.length();
21. //將寫文件指針移到文件尾。
22. randomFile.seek(fileLength);
23. randomFile.writeBytes(content);
24. randomFile.close();
25. } catch (IOException e) {
26. e.printStackTrace();
27. }
28. }
29.
30. /**
31. * B方法追加文件:使用FileWriter
32. * @param fileName
33. * @param content
34. */
35. public static void appendMethodB(String fileName, String content) {
36. try {
37. //打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
38. FileWriter writer = new FileWriter(fileName, true);
39. writer.write(content);
40. writer.close();
41. } catch (IOException e) {
42. e.printStackTrace();
43. }
44. }
45.
46. public static void main(String[] args) {
47. String fileName = "C:/temp/newTemp.txt";
48. String content = "new append!";
49. //按方法A追加文件
50. AppendToFile.appendMethodA(fileName, content);
51. AppendToFile.appendMethodA(fileName, "append end. \n");
52. //顯示文件內容
53. ReadFromFile.readFileByLines(fileName);
54. //按方法B追加文件
55. AppendToFile.appendMethodB(fileName, content);
56. AppendToFile.appendMethodB(fileName, "append end. \n");
57. //顯示文件內容
58. ReadFromFile.readFileByLines(fileName);
59. }
60. }

⑤ java 在eclipse工程下讀取文件內容和打成war包後,讀取同樣文件內容,正確讀取

首先war打完之後你可以用解壓軟體看看裡面的文件結構,和工程是不一樣的。沒有src/main/這一層。因此如果要滿足你的使用相對路徑要求,又要通用,只有兩個方法。

1、在項目下重新建一個resource資源包,配置文件放在裡面,然後根據resource相對路徑讀取
2、變更項目打包結構,打包輸出時把src/main/這層加上

總之這兩個方法的目的都是為了讓war包結構和你工程一致。

我的讀取配置文件方法如下,你可以參考下。文件路徑:

Stringpath=null;
try{
path=SellerProctController.class.getClassLoader()
.getResource("").toURI().getPath();
log.info("獲取到配置文件的路徑為:"+path);
}catch(URISyntaxExceptione){
log.error("獲取配置文件路徑出現異常,"+e.getMessage());
}
//把文件讀入文件輸入流,存入內存中
FileInputStreamfis=null;
try{
fis=newFileInputStream(newFile(path+"isa_addr.json"));
}catch(FileNotFoundExceptione){
log.error("讀取配置文件出現異常,"+e.getMessage());
}
//設置response的字元集為項目指定字元集
response.setCharacterEncoding("UTF-8");
//創建輸出流對象
PrintWriterout=null;
try{
out=response.getWriter();
}catch(IOExceptione){
log.error("創建輸出流對象失敗:"+e.getMessage());
}
Stringres=this.ReadFile(fis);
log.debug("最終獲得的Json串為:"+res);

⑥ java中怎樣從一個文件中讀取文件信息

java讀取文件路徑、所佔空間大小等文件消息,主要是使用FileInputStream類來操作,示例如下:

importjava.io.File;
importjava.io.FileInputStream;

publicclassceshi{
publicstaticvoidmain(String[]args)throwsException{

java.io.FilelocalFile=newFile("D:\1.txt");
FileInputStreamins=newFileInputStream(localFile);
intcountLen=ins.available();
byte[]m_binArray=newbyte[countLen];
ins.read(m_binArray);
ins.close();
System.out.println(localFile.getAbsoluteFile()+""
+localFile.getFreeSpace());
}
}

運行結果如下:

⑦ JAVA開發讀取文件的方法有哪些

/**
* 根據提供地址讀取文件返回字元串
* @param filePath
* @return 文件字元串
*/
private String readFile(String filePath){
File javaFile = new File(filePath);
StringBuffer fileStr = new StringBuffer();//存儲杜滸的文件字元串,.
int b;
InputStream fileIns = null;
InputStreamReader fileReder = null;
try {
fileIns = new FileInputStream(javaFile);
fileReder = new InputStreamReader(fileIns, "utf-8");
while ((b = fileReder.read()) != -1) {
fileStr.append((char) b);
}
// System.out.println(javaStr.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReder != null) {
fileReder.close();
}
if (fileIns != null) {
fileIns.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileStr.length()>0){
return fileStr.toString();
}else{
return "";
}
// System.out.println(result);
}
僅供參考!

⑧ java項目中文件的上傳與讀取

互聯網項目一般會有單獨的伺服器存放靜態資源,圖片就是一種靜態資源,在這里就是區別於項目部署的另一台伺服器。這時候你項目裡面都是使用相對路徑,像你上面所說的常量/opt/upload/這種做法是正確的,上傳圖片的時候,常見的有使用日期分目錄存儲的,如/opt/upload/2014/11/03/***.jpg,對於圖片的路徑,資料庫里一般來說保存到2014/11/03/***.jpg就可以了。這是存圖片。
取圖片,一般來說資源都必須發布服務才能讓外網訪問。例如,你可以在你項目中寫個servlet用來讀取圖片,如下面的服務地址http://ip:port/projectname/image/2014/11/03/***.jpg,其中2014前面的路徑是固定的,後面的是你資料庫里存儲的圖片地址,這時你頁面代碼裡面只需固定前綴http://ip:port/projectname/image + 圖片相對地址則可將圖片讀出來。
上面這種方法用的其實比較少,一般來說靜態伺服器都會部署一個web容器,然後使用單獨的域名,打個比方,你在靜態伺服器上有個tomcat,目錄/opt/tomcat/webapp/staticprojectname,staticprojectname是工程名,然後在上傳的所有圖片在staticprojectname下面,例如/opt/tomcat/webapp/staticprojectname/2014/11/03/***.jpg,然後在你原工程裡面直接使用http://靜態服務ip:port/staticprojectname/2014/11/03/***.jpg就可以訪問到圖片了,同樣的在你代碼裡面2014前面的地址是固定的,配置成常量,後面的則是資料庫里存的圖片相對地址。
說了這么多,有點亂,希望你能明白

閱讀全文

與java讀取工程文件相關的資料

熱點內容
pdf填色 瀏覽:145
ie運行java 瀏覽:637
單相空調壓縮機的構造 瀏覽:136
迅雷app的回收站在哪裡啊 瀏覽:595
加密技術的特點包括4點 瀏覽:561
pcre源碼包 瀏覽:67
崑山ug數控編程培訓 瀏覽:520
integer類源碼 瀏覽:819
java排序的時間復雜度 瀏覽:859
伺服器陣列卡壞了怎麼維修 瀏覽:537
shm演算法 瀏覽:520
可愛的程序員陸漓離開 瀏覽:608
如何把掃描文件做成pdf格式 瀏覽:626
php個性qq源碼 瀏覽:821
初學c語言顯示源未編譯 瀏覽:247
資產概況源碼 瀏覽:472
dos命令建文件夾命令 瀏覽:381
解壓的密碼htm被屏蔽 瀏覽:504
冬天太冷冰箱壓縮機不啟動怎麼辦 瀏覽:85
手機打開vcf需要什麼編譯器 瀏覽:912