gpt4 book ai didi

java - 写入和读取文件时出现问题

转载 作者:行者123 更新时间:2023-12-01 18:38:08 25 4
gpt4 key购买 nike

我是编程新手(抱歉,如果我问一个简单的问题),我的程序在处理文件写入和读取时遇到问题。首先,我询问用户他们想要的用户名和密码是什么。然后,为了简单地检查我所做的是否正确,我尝试读取该文件,然后打印出相同的信息。这是我的代码:

public void createAccount()
{
try
{
FileWriter doc = new FileWriter("Username.ctxt", true);
System.out.print("Enter your desired Username: ");
myUsername = keyboard.next();
System.out.println();
System.out.print("Enter your desired Password: ");
myPassword = keyboard.next();
System.out.println();
String doc2 = myUsername + " " + myPassword + "\n";
doc.write(doc2, 0, doc2.length());
doc.close();
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}

retrieveAccount();
}

public void retrieveAccount()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Username.ctxt"));//
String user = new String("");//username
String pass = new String("");//password
int stop;
String line = null;

System.out.print("Enter your username: ");//allows computer to search through file and find username
username = keyboard.next();
while ((line = reader.readLine()) != null)
{
scan = reader.readLine();
stop = scan.indexOf(" ");
user = scan.substring(0, stop);
System.out.println(user);
pass = scan.substring(stop + 1);
System.out.println(pass);
if(user.equals(myUsername))
{
System.out.println("Your password is: " + pass);
break;
}
}
}
catch(IOException a)
{
System.out.println("Error: " + a.getMessage());
}
}

所以我想要发生的是:

Enter desired username: jake101
Enter desired password: coolKid

Enter your username: jake101
your password is: coolKid

但实际发生的是,是越界异常(-1)

发生这种情况是因为当我使用 indexOf(""); 时它会搜索空格。当它返回负 1 时,意味着没有空间。我相信正在发生的事情是我没有写入我试图读取的同一个文档。如果有人可以帮助我找出我做错了什么,这会有所帮助!

最佳答案

您正在重复读取文件的内容...

您首先使用...从文件中读取一行

while ((line = reader.readLine()) != null) {

紧接着,您使用...阅读了另一行

String scan = reader.readLine();

删除第二行读取...

关于java - 写入和读取文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20942211/

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