vinoth vinoth - 2 years ago 89
Java Question

File handling in java

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

}

}

Answer Source

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:

 System.out.println( System.getProperty( "user.dir" ) );

You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download