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 The hi.html is present in the same directory as

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;

File file = new File("hi.html");

boolean p = file.exists();

int i = fis.available();

fis = new FileInputStream(file);

int ch =, 0, 1024);

output.write(bytes, 0, ch);
ch =, 0, 1024);

}catch(Exception e){
String errorMessage = "file not found";
}finally {
if(fis != null){



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