File Input Validation.

This code performs file input validation by checking whether the file exist and prompting the user for the name of the file two more times, if after 2nd time file doesn’t exist exit with an exception.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
/*
 * file input validation with
 * try and catch exception
 * 
 */
package test1;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Main {
    static String[] words = new String[5];
    public static void main(String[] args) 
    {
        Scanner kb = new Scanner(System.in);
 
        System.out.println("enter file name:");
        String fileName = kb.next();
 
        try {
 
            int i = 0;
            File inFile = new File(fileName);
 
            //if file does not open ask the user 2 more times
            while (!inFile.exists() && i++ < 2) {
                System.out.println("enter file name:");
                fileName = kb.next();
                inFile = new File(fileName);
            }
            Scanner in = new Scanner(new File(fileName));
 
            int j = 0;            
            while(in.hasNext())
            {
                words[j] = in.next();
                j++;
            }
 
            System.out.println(Arrays.toString(words));
 
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }        
}
Share This!

Leave a Reply

Your email address will not be published.