[英]How to read and validate different portions of a line of text in a text file in Java?
因此,我正在嘗試使用Java驗證文本文件中的數據。 文本文件如下所示(忽略要點):
數字的第一列必須在00000-99999范圍內且沒有字母,第二列必須在0-5范圍內,第三列必須在0.00-100.00范圍內。 那么,如何才能分別驗證文本文件中的每個列以滿足要求? 我已經知道如何讀取文本文件,我只是想弄清楚如何驗證數據。
因此,您有一行, String line = "20034 4 103.90";
。
您可以使用.split()
將其分解為組成部分。
然后分別檢查/驗證它們中的每一個,然后在下一行重復相同的操作。
因此,它將由定界符" "
分割,因為它分隔了列。
String[] parts = line.split(" ");
String part1 = parts[0]; // 20034
String part2 = parts[1]; // 4
String part3 = parts[2]; // 203.90
您可以在這里玩耍http://ideone.com/LcNYQ9
關於驗證,這很容易。
if (i > 0 && i < 100000)
if (i > 0 && i < 6)
, if (i > 0 && i < 6)
與列2相同 要檢查第一列是否不包含任何字母,可以使用以下命令:
part1.contains("[a-zA-Z]+") == false
在if
語句中為part1.contains("[a-zA-Z]+") == false
。
而不是檢查它是否沒有字母,而是檢查它僅包含數字或小數點 。 我提供了適當的正則表達式來執行相同的操作。
步驟1:將文件中的每一行放入List<String>
:
List<String> list = Files.readAllLines(Paths.get("filepath"));
第2步:將每一行拆分成各個部分,並分別進行驗證:
for(String str : list)
{
String[] arr = list.split(" ");
if(arr[0].matches("\\d+")) // Check to see if it only contains digits
int part1 = Integer.valueOf(arr[0]);
else
//throw appropriate exception
validate(part1, minAcceptedValue, maxAcceptedValue);
if(arr[1].matches("\\d+")) // Check to see if it only contains digits
int part2 = Integer.valueOf(arr[1]);
else
//throw appropriate exception
validate(part2, minAcceptedValue, maxAcceptedValue);
if(arr[2].matches("[0-9]{1,4}(\\.[0-9]*)?")) // Check to see if it is a Double that has maximum 4 digits before decimal point. You can change this to any value you like.
int part2 = Integer.valueOf(arr[2]);
else
//throw appropriate exception
validate(part3, minAcceptedValue, maxAcceptedValue);
}
void validate(int x, int min, int max)
{
if(x < min || x > max)
//throw appropriate exception
}
您可以使用Scanner
( javadocs )幫助您解析輸入。 它與正則表達式解決方案相似,但是它是針對您從潛在的巨大文本文件中讀取一系列值的情況而量身定制的。
try (Scanner sc = new Scanner(new File(...))) {
while (sc.hasNext()) {
int first = sc.nextInt();
int second = sc.nextInt();
float third = sc.nextFloat();
String tail = sc.nextLine();
// validate ranges
// validate tail is empty
}
}
當然,您可能會捕獲任何潛在的異常並將其視為驗證失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.