簡體   English   中英

當程序在Eclipse IDE中運行且沒有任何錯誤時,無法使用Java Applet中的FileReader打開文件

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

我正在寫一個applet。 當我在命令提示符下運行代碼時,它顯示文件未找到異常。 該程序在Eclipse IDE中運行良好。 誰能告訴我可能是什么錯誤?

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

如果目標文件與您的應用程序不在同一目錄中,則會發生這種情況。

使用String file = openfile.getDirectory() + File.separator + openfile.getFile(); 獲取目標文件的絕對路徑。

您需要指定目錄

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

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM