私は、ファイルの入力をユーザに求めていて、ファイルが存在しない場合、どのように私はプログラム停止せずにファイル名を求めるために続けることができますか?

オーボエ:

これは、私はそれがFileクラスからループまたは多分.empty()メソッドを必要とすべきである知っているが、私は確かに...すべてのヘルプは高く評価されていないよ...私が持っているものです。私が持っていることは、ファイルを開いて、各ライン上のファイルから読み込まれ、その後、ファイル内の文字の量、ファイル内の単語の量、およびファイル内の文の数を裏返します。

public class FileExample{
    public static void main(String[] args) throws FileNotFoundException, IOException{
        Scanner in = new Scanner(System.in);
        boolean fileFound = false;
        try{
            System.out.println("What is the name of the file?");
            inputFile = in.nextLine();
            File file = new File(inputFile);
            fileFound = file.exists();
            FileInputStream fileStream = new FileInputStream(file); 
            InputStreamReader input = new InputStreamReader(fileStream);
            BufferedReader reader = new BufferedReader(input);
            if(!file.exists()){

            }
            while((line = reader.readLine()) != null){
                if(!(line.equals(""))){
                    ...
                }
            }
        }
        catch(FileNotFoundException e){
            System.out.println("File not found.");
        }
        System.out.println("output data");
    }   
}
Nosrep:

あなたは、whileループを作り、ループ内のtryブロックを移動する必要があります。

while(true){
    try{
        System.out.println("What is the name of the file?");
        inputFile = in.nextLine();
        File file = new File(inputFile);
        if(!file.exists()){
            continue;
        }
        FileInputStream fileStream = new FileInputStream(file); 
        InputStreamReader input = new InputStreamReader(fileStream);
        BufferedReader reader = new BufferedReader(input);
        while((line = reader.readLine()) != null){
            if(!(line.equals(""))){
                characterCount += line.length();
                String[] wordList = line.split("\\s+");
                countWord += wordList.length;
                String[] sentenseList = line.split("[!?.:]+");
                sentenseCount += sentenseList.length;
            }
        }
        break;
    }
    catch(FileNotFoundException e){
        System.out.println("File not found.");
    }
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=397198&siteId=1