简体   繁体   English

Java输入验证方法

[英]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. 我对Java有点陌生,正在学习有关输入验证方法的信息,但是我正在努力完成要完成的任务。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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