[英]How do I validate text file contents in Java?
我正在創建一個讀取 .txt 文件內容的程序,它會驗證該文件的內容,然后將該文件的內容輸出到一個漂亮的格式化表格中。 我的程序當前讀取文件然后輸出內容,我正在嘗試實現對所述文件內容的驗證。
我現在將解釋我的程序讀取文件的方式:
.txt 內容:
firstname lastname
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
txt 文件包含以下格式的數據:
{gamename} : {gamescore} : {minutesplayed}
要閱讀我使用的 .txt:
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
然后拆分數據,我在從 a 到 g 的每個字母上使用此 for 循環,如下所示:
//~~~~a-line-split~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
為了通過驗證進行澄清,我需要通知用戶某行是否缺少數據,例如,如果第一行有:
游戲一:{失蹤}:1428
目前我對每一行都有這個簡單的 if 語句:
if (bline.length < 3)
{
System.out.println("There is an error in row one!");
}
但是我需要讓程序准確地知道每行數據丟失的位置。 不只是一般的回應:
System.out.println("There is an error in row one!");
但取而代之的是:
System.out.println("There is data missing, row: 1 column: 2");
要求的完整代碼:
package readfile;
import java.io.*;
import java.util.*;
public class readfile
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String FileN = " ";
String a = " ";
String b = " ";
String c = " ";
String d = " ";
String e = " ";
String f = " ";
String g = " ";
boolean fileExists = false;
File newFile = null;
while(!fileExists)
{
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
newFile = new File(FileN);
fileExists = newFile.exists();
if (!fileExists)
{
System.out.println(FileN + " not found...");
}
}
try {
Scanner scan2;
scan = new Scanner(newFile);
}
catch(FileNotFoundException fnfe) {
System.out.println("sorry but the file doesn't seem to exist");
}
//++++++++++++++=FILE READ=++++++++++++++++++++
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
//+++++++++++++++ARRAYS FOR THE LINES+++++++++++++++++++
//~~~~A-LINE~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
//~~~~B-LINE~~~~//
String[] bline;
bline = b.split(":");
for (int i=0; i<bline.length; i++)
{
bline[i] = bline[i].trim();
//System.out.println(bline[i]);
}
//~~~~C-LINE~~~~//
String[] cline;
cline = c.split(":");
for (int i=0; i<cline.length; i++)
{
cline[i] = cline[i].trim();
//System.out.println(cline[i]);
}
//~~~~D-LINE~~~~//
String[] dline;
dline = d.split(":");
for (int i=0; i<dline.length; i++)
{
dline[i] = dline[i].trim();
//System.out.println(dline[i]);
}
//~~~~e-LINE~~~~//
String[] eline;
eline = e.split(":");
for (int i=0; i<eline.length; i++)
{
eline[i] = eline[i].trim();
//System.out.println(eline[i]);
}
//~~~~f-LINE~~~~//
String[] fline;
fline = f.split(":");
for (int i=0; i<fline.length; i++)
{
fline[i] = fline[i].trim();
//System.out.println(fline[i]);
}
//~~~~g-LINE~~~~//
String[] gline;
gline = g.split(":");
for (int i=0; i<gline.length; i++)
{
gline[i] = gline[i].trim();
//System.out.println(gline[i]);
}
String user = aline [0];
//~~~~~~~~~GAME NAMES~~~~~~~~~~~~~//
//GTA
String gameone = bline [0];
//MINECRAFT
String gametwo = cline [0];
//ASSASSIN'S CREED IV
String gamethree = dline [0];
//PAYDAY2
String gamefour = eline [0];
//WOLFENSTEIN
String gamefive = fline [0];
//FARCRY 4
String gamesix = gline [0];
//~~~~~~~~~~Achievement Score~~~~~~~~~~~~//
//GTA SCORE
String scoreone = bline [1];
//MINECRAFT SCORE
String scoretwo = cline [1];
//ASSASSIN'S CREED IV SCORE
String scorethree = dline [1];
//PAYDAY2 SCORE
String scorefour = eline [1];
//WOLFENSTEIN SCORE
String scorefive = fline [1];
//FARCRY 4 SCORE
String scoresix = gline [1];
//+++++++++++++++++++++TOTAL~~CALC++++++++++++++++++++++//
double totalcount = 79.566; // change to the amount played.
int totalhours = (int)totalcount;
int totalmin = (int)(totalcount*60)%60;
int totalsec = (int)(totalcount*(60*60))%60;
System.out.println("TOTAL TIME PLAYED:");
System.out.println(String.format("%s(hours) %s(minutes) %s(seconds)",
totalhours, totalmin, totalsec));
//~~~~~~~~~~Minutes Played~~~~~~~~~~~~//
//GTA min
String minone = bline [2];
//MINECRAFT min
String mintwo = cline [2];
//ASSASSIN'S CREED IV min
String minthree = dline [2];
//PAYDAY2 min
String minfour = eline [2];
//WOLFENSTEIN min
String minfive = fline [2];
//FARCRY 4 min
String minsix = gline [2];
//~~~~~~~~~GAMES TEST~~~~~~~~~~~~//
System.out.println("\nUSER: "+user);
System.out.println("\nDATA: ");
System.out.println("1: "+gameone+" | score: "+scoreone+"
| minutes played: "+minone);
System.out.println("2: "+gametwo+" | score: "+scoretwo+"
| minutes played: "+mintwo);
System.out.println("3: "+gamethree+" | score: "+scorethree+"
| minutes played: "+minthree);
System.out.println("4: "+gamefour+" | score:
"+scorefour+" | minutes played: "+minfour);
System.out.println("5: "+gamefive+" | score: "+scorefive+"
| minutes played: "+minfive);
System.out.println("6: "+gamesix+" | score: "+scoresix+"
| minutes played: "+minsix);
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two
column "+(i+1));
}
}
}
}
}
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two column "+(i+1));
}
}
}
沒有測試這個,但它應該工作
編輯:
查看您的完整代碼bline[2], cline[2]...
等等,如果這些值首先從文件中丟失,那么會給您一個 Index Out of bounds 異常,因此在進行該調用之前,您應該執行首先檢查您可以創建一個靜態方法來進行檢查
public static String getAtIndex(String[] array, int indexToCkeck){
if(indexToCkeck >=array.length){
return "";
}
else{
return array[indexToCkeck];
}
}
因此,不要使用bline[2], cline[2] ...
使用readfile.getAtIndex(bline, 2)
這樣如果信息丟失,它將返回一個空字符串
也沒有測試,不過應該沒問題
使用經過良好測試的庫,如supercsv或任何其他. 一旦您的文本格式變得更加復雜,這將為您節省一些時間。 它還提供了一組很好的內置數據類型,用於驗證數據的每一列。 您也可以將數據直接映射到 POJO,這在某些情況下會很方便。
要將每一行加載到地圖中,您可以執行以下操作:
在 stack47220687.txt 中准備您的文件:
Gamename: Gamescore: Minutestoplay
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
並使用這樣的東西
package stack47220687;
import java.io.FileReader;
import java.util.Map;
import org.junit.Test;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
public class HowToReadACSVFile {
private static final CsvPreference COLON_DELIMITED = new CsvPreference.Builder('"', ':', "\n").build();
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // gamename
new NotNull(), // gamescore
new NotNull(), // minutestoplay
};
return processors;
}
@Test
public void read() throws Exception {
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(
Thread.currentThread().getContextClassLoader().getResource("stack47220687.txt").getPath()),
COLON_DELIMITED);
// the header columns are used as the keys to the Map
final String[] header = mapReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Map<String, Object> oneRecordInAMap;
while ((oneRecordInAMap = mapReader.read(header, processors)) != null) {
System.out.println(String.format("lineNo=%s, rowNo=%s, this line stored in a map=%s",
mapReader.getLineNumber(), mapReader.getRowNumber(), oneRecordInAMap));
/**
* oneRecordInAMap.get("Gamescore");
*/
}
} finally {
if (mapReader != null) {
mapReader.close();
}
}
}
}
適用於超級 csv 2.4.0
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
並將打印
lineNo=2, rowNo=2, this line stored in a map={ Gamescore= 120 , Gamename=Gameone , Minutestoplay= 1428 }
lineNo=3, rowNo=3, this line stored in a map={ Gamescore= 20 , Gamename=Gametwo , Minutestoplay= 10 }
lineNo=4, rowNo=4, this line stored in a map={ Gamescore= 90 , Gamename=Gamethree , Minutestoplay= 800 }
lineNo=5, rowNo=5, this line stored in a map={ Gamescore= 190 , Gamename=Gamefour , Minutestoplay= 2001 }
lineNo=6, rowNo=6, this line stored in a map={ Gamescore= 25 , Gamename=Gamefive , Minutestoplay= 80 }
lineNo=7, rowNo=7, this line stored in a map={ Gamescore= 55 , Gamename=Gamesix , Minutestoplay= 862}
如果您的格式不正確,它還會提供有意義的錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.