[英]Input Validation method for Java
我对Java有点陌生,正在学习有关输入验证方法的信息,但是我正在努力完成要完成的任务。 有人能帮我吗? 以下代码正在读取计算机上某处的文件。 我应该使用输入验证方法来验证文件路径是否正确。 这是我到目前为止的内容:
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();
}
}
}
}
判断给定的文件路径是否正确的最简单方法是简单地检查其是否存在:
if (inputFile.exists() && !inputFile.isDirectory()) {
// inputFile has a valid path.
}
使用以下代码检查。
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.