简体   繁体   中英

Input Validation method for Java

I'm sort of new to Java and I'm learning about input validation methods but I'm struggling with an assignment that I'm trying to complete. Can someone help me? The following code is reading a file somewhere on your computer. I'm supposed to verify that the file path is correct with an input validation method. This is what I have so far:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class readFile {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter the name of your File: ");
    String fileName = scan.nextLine();
    File inputFile = new File(fileName);
    BufferedReader reader = null;

    try {
        String sCurrentLine;
        reader = new BufferedReader(new FileReader(inputFile));
        while ((sCurrentLine = reader.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.out.print(e.getMessage());

    } finally {

        try {
            if (reader != null)reader.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();

        }   
    }
}

}

The easiest way to tell if the file path given is correct is to simply check if it exists:

if (inputFile.exists() && !inputFile.isDirectory()) {
    // inputFile has a valid path.
}

Use following code checking.

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM