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

时间:2014-01-06 02:54:24

标签: java

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

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时,意味着没有空间。我相信正在发生的事情是我不是在写一篇我想读的文件。如果有人能帮助我弄清楚我做错了什么会有所帮助!

4 个答案:

答案 0 :(得分:3)

你是双重读取文件的内容......

您首先使用...

从文件中读取一行
while ((line = reader.readLine()) != null) {

直到那之后,你用...读了另一行

String scan = reader.readLine();

摆脱第二行阅读...

答案 1 :(得分:1)

问题是你在同一个循环中调用了readline两次

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

将上述内容更改为以下内容,它将起作用

    while ((line = reader.readLine()) != null) 
    {
       String scan = line;

答案 2 :(得分:0)

问题似乎出在您的 retrieveAccount()方法中,请尝试关闭您的 reader 对象。你已经在 retrieveAccount()中打开了文件并且从未关闭(因此其stil处于锁定状态,以便其他applns / mthds / threads访问)。

尝试在try block结束前添加reader.close()

答案 3 :(得分:0)

我建议你为createAccount,retrieveAccount,writeToFile和readToFile创建单独的方法。方法应始终负责处理单个模块。 createAccount方法的实际责任是从文件中读取吗?我完全会说不。首先,因为没有遵循低耦合 - 高内聚原则,其次,因为这种方式不存在可重用性。您的当前方法还会出现其他问题,但由于您仍处于初期阶段,因此需要这样做。

我将为您提供一些您可以做的事情的部分,但是,有些部分您应该自己动手,比如创建用户类(这应该不会很困难,它会帮助您学习)

让我们看看。

 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,无论它出现在哪里。

  • 您的用户类应实现可比较的并包含下述方法:

    public int compareTo(User user) {
    
    }
    
    public boolean equals(Object user) {
    
    }
    
  • 总是尝试创建“即插即用”方法(非硬编码),这就是我作为参数传递给userList的原因。

  • 请注意,如果您不使用泛型,可能需要进行类型转换。否则,您将收到编译错误。

  • 如果您有任何疑问,请与我们联系。