我有以下代码。
以下源代码来自文件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();
}
}
}
最佳答案
.java文件的目录不一定是你代码运行的方向!您可以通过以下示例检查程序的当前工作目录:
System.out.println( System.getProperty( "user.dir" ) );
您可以使用 System.getProperty( "user.dir") 字符串使您的相对文件名成为绝对文件名!只需将其作为您的文件名的前缀:)
关于java - java中的文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6269406/