java中的文件处理
我有下面的代码。
下面的源代码来自文件 x.java。 hi.html 与 x.java 位于同一目录中。
即使文件存在,我也收到文件未找到异常。我错过了什么吗?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Exception e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}
I have the below code.
The below source code is from the file x.java. The hi.html is present in the same directory as x.java.
I get a file not found exception even though the file is present. Am I missing something ?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Exception e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
.java文件的目录不一定是你的代码运行的方向!您可以通过以下示例检查程序的当前工作目录:
您可以使用 System.getProperty( "user.dir" ) 字符串使相对文件名成为绝对文件名!只需将其添加到您的文件名前面即可:)
The directory of the .java file is not necessarily the direction your code runs in! You can check the current working dir of your program by in example:
You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)
查看您的“user.dir”属性。
程序将在此处开始搜索没有完整路径的文件。
Take a look at your "user.dir" property.
That's where the program will root its search for files that don't have a complete path.
从属性文件获取键值的代码
System.getProperty("user.dir")
to return the directory that you are running the Java app from.Code to get Key-Value from Property files
我猜你会得到一个 NullPointerException:
然后调用:
将导致一个 NullPointerException ,因为稍后对
fis
进行第一个非空赋值:I guess you get a
NullPointerException
:then the call:
will result in an
NullPointerException
as the first non-null assignment tofis
is later: