导航:首页 > 编程语言 > 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读取工程文件相关的资料

热点内容
初学c语言显示源未编译 浏览:245
资产概况源码 浏览:472
dos命令建文件夹命令 浏览:378
解压的密码htm被屏蔽 浏览:502
冬天太冷冰箱压缩机不启动怎么办 浏览:83
手机打开vcf需要什么编译器 浏览:910
加密磁盘后开机很慢 浏览:271
长沙智能云控系统源码 浏览:258
阿里云服务器如何设置操作系统 浏览:999
超级命令的英文 浏览:783
做账为什么要用加密狗 浏览:586
考研群体怎么解压 浏览:159
linux修改命令提示符 浏览:226
圆圈里面k图标是什么app 浏览:63
pdf加空白页 浏览:948
linux服务器如何看网卡状态 浏览:318
解压新奇特视频 浏览:707
图书信息管理系统java 浏览:554
各种直线命令详解 浏览:864
程序员泪奔 浏览:147