Search code examples
javaappletfilenotfoundexceptionfilewriter

Unable to open a file using FileReader in java applet while the programs runs without any error in Eclipse IDE


I'm writing an applet. When i am running the code in command prompt it shows a file not found exception. The program is running pretty fine in Eclipse IDE. Can anyone tell what could be the error?

Frame frame= new Frame();
FileDialog openfile= new FileDialog(frame,"Select a file", FileDialog.LOAD);
openfile.setVisible(true);
String file=openfile.getFile();
System.out.println(file);
try{
FileReader f= new FileReader(file);
BufferedReader br= new BufferedReader(f);
Scanner in=new Scanner(br);
while(in.hasNextInt()){
n=in.nextInt();
count++;
sum += n;
System.out.println(n);

}
System.out.println("Count:" + count);

Solution

  • This happens if the target file is not in the same directory as your application.

    Use String file = openfile.getDirectory() + File.separator + openfile.getFile(); to get the absolute path to the target file.