gpt4 book ai didi

java - 文件未找到异常,不知道是什么原因

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:14 25 4
gpt4 key购买 nike

我应该使用文本文件的输入创建一个字符串数组,但我无法正确读取文本文件。我的文本文件和程序位于同一文件夹中,我做错了什么?

package A2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;

public class a2main {
public static final Scanner SCANNER = new Scanner(System.in);
String[] winners;

public static void main(String[]args) throws FileNotFoundException{ //main method
String teamName = getInput();
createArray();
int wins = calcTeamWins(teamName);
printWins(teamName, wins);
}

public static int calcTeamWins(String TeamName){ //Scans the array and returns team wins
return 0;
}

public static String getInput(){ // Method to get input from user.
System.out.println("Please enter the name of the team you'd like to choose.");
return SCANNER.next();
}

public static String[] createArray() throws FileNotFoundException{ //Method used to create and fill array of winners.
final int ARRAY_LENGTH = 104;
String[] winnerArray = new String[ARRAY_LENGTH];
File WSW = new File("WorldSeriesWinners.txt");
Scanner inputFile = new Scanner(WSW);

for(int i = 0; i < ARRAY_LENGTH-1; i++){
while(inputFile.hasNext()){
winnerArray[i] = inputFile.nextLine();
System.out.println(winnerArray[i]);
}
}
inputFile.close();
return winnerArray;
}
public static void printWins(String TeamName, int Wins){ //Method used to print team anem + wins
System.out.println("The " + TeamName + " have won " + Wins + " World Series.");
}

}

它应该读取的文本文件是 WorldSeriesWinners.txt 该文件是一个多行 txt,每行都有一个字符串。

最佳答案

Java 的执行位置和文件所在位置之间存在差异。它不是从类所在的同一目录中查找。

既然已经打包了,就需要将其添加到路径中。

尝试如下:

   new File(System.getProperty("user.dir") + "/A2/" + "WorldSeriesWinners.txt")

关于java - 文件未找到异常,不知道是什么原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com