[英]Problems writing to and reading from a file
我是編程新手(很抱歉,如果我問一個簡單的問題),我的程序在處理文件寫入和讀取操作時遇到問題。 首先,我問用戶他們想要他們的用戶名和密碼是什么。 然后,為了簡單地檢查我的操作是否正確,我嘗試讀取該文件,然后打印出相同的信息。 這是我的代碼:
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();
擺脫第二行閱讀...
問題是您在同一循環中兩次調用readline
while ((line = reader.readLine()) != null)
{
scan = reader.readLine();
將以上更改為以下內容,它將起作用
while ((line = reader.readLine()) != null)
{
String scan = line;
object. 問題似乎出在您的restoreAccount()方法中,請嘗試關閉您的對象。 您已經在retrieveAccount()中打開了該文件,並且從未關閉過(因此,它的stil在鎖定狀態下可供其他applns / mthds / threads訪問)。
嘗試在try塊結束之前添加reader.close()
我建議您為createAccount,retrieveAccount,writeToFile和readToFile創建單獨的方法。 一個方法應該始終負責處理單個模塊。 createAccount方法的實際責任是從文件讀取嗎? 我會完全拒絕。 首先,因為不遵循低耦合-高內聚性原則,其次,因為不存在可復用性。 正確的方法還會發生其他問題,但是由於您仍處於起步階段,因此可以預期。
我將為您提供一些您可以做的事情,但是,有些事情您應該自己完成,例如創建User Class(這並不難,它將幫助您學習)。
讓我們來看看。
public void createAccount(User user, ListInterface<User> userList)
throws AuthenticationException {
if (!userList.exists(user)) {
userList.append(user);
} else {
throw new AuthenticationException(
"You cannot add this user. User already exists!");
}
}
public boolean authenticate(User user, ListInterface<User> userList)
throws AuthenticationException {
for (int i = 1; i <= userList.size(); i++) {
if (user.equals(userList.get(i))
&& user.getPassword().equals(
userList.get(i).getPassword())) {
return true;
}
}
return false;
}
public void readFromFile(String fileName, ListInterface<User> userList) {
String oneLine, oneLine2;
User user;
try {
/*
* Create a FileWriter object that handles the low-level details of
* reading
*/
FileReader theFile = new FileReader(fileName);
/*
* Create a BufferedReader object to wrap around the FileWriter
* object
*/
/* This allows the use of high-level methods like readline */
BufferedReader fileIn = new BufferedReader(theFile);
/* Read the first line of the file */
oneLine = fileIn.readLine();
/*
* Read the rest of the lines of the file and output them on the
* screen
*/
while (oneLine != null) /* A null string indicates the end of file */
{
oneLine2 = fileIn.readLine();
user = new User(oneLine, oneLine2);
oneLine = fileIn.readLine();
userList.append(user);
}
/* Close the file so that it is no longer accessible to the program */
fileIn.close();
}
/*
* Handle the exception thrown by the FileReader constructor if file is
* not found
*/
catch (FileNotFoundException e) {
System.out.println("Unable to locate the file: " + fileName);
}
/* Handle the exception thrown by the FileReader methods */
catch (IOException e) {
System.out.println("There was a problem reading the file: "
+ fileName);
}
} /* End of method readFromFile */
public void writeToFile(String fileName, ListInterface<User> userList) {
try {
/*
* Create a FileWriter object that handles the low-level details of
* writing
*/
FileWriter theFile = new FileWriter(fileName);
/* Create a PrintWriter object to wrap around the FileWriter object */
/* This allows the use of high-level methods like println */
PrintWriter fileOut = new PrintWriter(theFile);
/* Print some lines to the file using the println method */
for (int i = 1; i <= userList.size(); i++) {
fileOut.println(userList.get(i).getUsername());
fileOut.println(userList.get(i).getPassword());
}
/* Close the file so that it is no longer accessible to the program */
fileOut.close();
}
/* Handle the exception thrown by the FileWriter methods */
catch (IOException e) {
System.out.println("Problem writing to the file");
}
} /* End of method writeToFile */
有用的信息:
userList是使用泛型(ListInterface<User>)
的動態鏈表。
如果您不想使用泛型,則可以說ListInterface userList,無論出現在哪里。
您的User類應實現可比較類,並包括以下所述的方法:
public int compareTo(User user) { } public boolean equals(Object user) { }
始終嘗試創建“即插即用”方法(未硬編碼),這就是我將userList作為參數傳遞的原因。
請注意,如果您不使用泛型,則可能需要進行類型轉換。 否則,您將獲得編譯錯誤。
如果您有任何問題,請通知我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.