我正在尝试从名为“ inData.txt”的文本文件中加载程序的数据,并将其输出到文件“ out.txt”中,基本上模仿了保存。问题是,当我通过GUI运行此代码时,它不会加载到文本区域,但可以保存。我不知道我的GUI代码或League文件中的代码是否有问题。
我尝试检查文本文件是否更改,但是没有更改,但是代码运行时没有错误。
//League.java
private static final String READ_FILE="inData.txt";
private static final String OUT_FILE="out.txt.";
public void readFromFile() //throwsIO exception /take from file into arraylist
{
//reading the inData.txt file and loading the arraylist
//with each instantiated object from the data
try
{
Scanner in = new Scanner(new File(READ_FILE));
//loop through the file and read each valie and create an object
while(in.hasNextLine())
{
String name = in.nextLine();
System.out.println ("read name: " + name);
String coach = in.nextLine();
System.out.println ("read coach: " + coach);
int teamID = in.nextInt();
System.out.println ("read team ID: " + teamID);
int wins = in.nextInt();
System.out.println ("read wins: " + wins);
int losses = in.nextInt();
in.nextLine();
System.out.println ("read losses: " + losses);
String player1 = in.nextLine();
System.out.println ("read player 1 name: " + player1);
String position1 = in.nextLine();
System.out.println ("read player 1 position: " + position1);
Player p1 = new Player(player1, position1);
String player2 = in.nextLine();
System.out.println ("read player 2 name: " + player2);
String position2 = in.nextLine();
System.out.println ("read player 2 position: " + position2);
Player p2 = new Player(player2, position2);
String player3 = in.nextLine();
System.out.println ("read player 3: " + player3);
String position3 = in.nextLine();
System.out.println ("read player 3 position: " + position3);
Player p3 = new Player(player3, position3);
//create and Item object
Team newTeam = new Team(name, coach, teamID, wins, losses, p1, p2, p3);
league.add(newTeam);
}
}
catch(IOException e)
{
System.out.println ("Error with file loading");
}
}
readFromFile()的预期结果是从inData.txt获取信息并将其导入GUI。
答案 0 :(得分:0)
文件内容是什么样的?
鉴于您正在逐行循环,建议您始终使用nextLine()并根据需要解析从中获取的字符串。例如,如果您的文件内容如下所示:
line1
23:34:45:99
34
您可以这样做:
if (in.hasNextLine()){
String firstLine = in.nextLine();
String secondLine = in.nextLine();
int[] nums = new int[3];
int i = 0;
for (String intString : lineTwo.split(":")) {
nums[i] = Integer.valueOf(intString);
i++;
}
// or simply:
int thirdLine = Integer.valueOf(in.next());
// if you just have one int per line anyway
}
我猜您遇到的问题涉及一些稍微高级的主题,例如代码点或换行符与回车符之间的区别,如果您想了解Scanner的复杂性,可能会对您感兴趣。 / p>
让我知道这实际上是否不是您遇到的问题,我将编辑我的答复。