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);
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.
You need to specify the directory
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileReader1 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int sum=0,count=0,n;
Frame frame= new Frame();
FileDialog openfile= new FileDialog(frame,"Select a file", FileDialog.LOAD);
openfile.setVisible(true);
String dir=openfile.getDirectory();
String file = openfile.getFile();
File ff = new File(dir+file);
FileReader fr = null;
BufferedReader br = null;
Scanner in = null;
System.out.println(dir+file);
try{
fr = new FileReader(ff);
br = new BufferedReader(fr);
in=new Scanner(br);
while(in.hasNextInt()){
n=in.nextInt();
count++;
sum += n;
System.out.println(n);
}
System.out.println("Count:" + count);
}catch(Exception e){
System.out.println("Exception"+e);
}finally{
fr.close();
br.close();
in.close();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.