繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM