[英]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.