有一種方法可以接收檔案路徑,然后檢查該檔案的內容。專案檔案結構為:
filePathTesting
┣??test
┃ ┣ ??TestCard.java
┃ ┣ ??TestCardGame.java
┃ ┗ ??valid5PlayersPack.txt
┗??src
┣ ??App.java
┣ ??Card.java
┗ ??CardGame.java
src/CardGame.java 中的方法
public static boolean isValidPackFile(String packLocation, int numPlayers)
{
File file = new File(packLocation);
if (file.exists() && file.isFile()){
try (BufferedReader reader=new BufferedReader(new FileReader(packLocation))){
String line;
int lineCount = 0;
while((line=reader.readLine())!=null){
try {
int num = Integer.parseInt(line);
if (num<=0){
System.out.println("ERROR: Pack file contains a non-positive integer");
return false;
}
lineCount ;
} catch (NumberFormatException e) {
System.out.println("ERROR: Pack file contains a non-integer");
return false;
}
}
if(lineCount==numPlayers*8){
return true;
}else{
System.out.println("ERROR: There are not " 8*numPlayers " cards in the pack file");
return false;
}
}catch(IOException e){
System.out.println("ERROR: Could not read pack file");
return false;
}
}
else {
System.out.println("ERROR: Pack file does not exist");
return false;
}
}
test/TestCardGame.java 中的測驗方法
@Test
public void testIsValidPackFileValidFile() throws IOException{
int numPlayers=5;
String filePath="valid5PlayersPack.txt";
System.out.println(new File(".").getAbsolutePath());
assertTrue("Valid file not recognised as valid", CardGame.isValidPackFile(filePath, numPlayers));
}
運行 CardGame.java 時,將“test/valid5PlayersPack.txt”作為檔案路徑傳遞,按預期作業,沒有遇到錯誤。
使用 JUnit 測驗方法并傳入完全相同的檔案路徑時,找不到檔案。也試過傳入:
valid5PlayersPack.txt
../test/valid5PlayersPack.txt
../valid5PlayersPack.txt
src/test/valid5PlayersPack.txt
../test/valid5PlayersPack.txt
但每次它說沒有找到檔案
我嘗試傳入相對于 TestCardGame 和 CardGame 的檔案路徑,但永遠無法獲得有效的檔案路徑。
我也用過:
System.out.println(new File(".").getAbsolutePath());
路徑的最后一位是“filePathTesting_dba1f5ce/”。這一切似乎都是正確的
任何幫助將不勝感激。
uj5u.com熱心網友回復:
問題是 JUnit 在運行時使用的作業目錄與類實際使用的目錄不同。非常感謝@TimMoore 的幫助。解決方案是更改 settings.json 中 java.test.config 的作業目錄
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530152.html
標籤:爪哇文件小路
上一篇:更新檔案中的資料
