首页 > 解决方案 > 如何使用 PrintWriter 仅删除文件中的几个字符

问题描述

我使用以下代码在 Java 中创建了一个帐户系统:

while (true) {
        Scanner s = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(new FileWriter("C:\\Users\\nisha\\IdeaProjects\\LeetCode\\src\\com\\company\\Accounts", true), true);
        boolean shouldContinue = false;

        System.out.println("Do you want to create an account (type create) or login to an account (type login) or exit (type exit)?");
        String response = s.nextLine();

        if (response.equals("create")) {
            System.out.println("What do you want your username to be?");
            String username = s.nextLine();

            if (username.equals("exit"))
                return;

            int len = username.length();
            Scanner scanner = new Scanner(new File("C:\\Users\\nisha\\IdeaProjects\\LeetCode\\src\\com\\company\\Accounts"));

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                if (line.length() < len)
                    continue;

                if (line.substring(0, len).equals(username)) {
                    System.err.println("Username already exist");
                    shouldContinue = true;
                    break;
                }
            }

            if (shouldContinue)
                continue;

            System.out.println("What is the your value (number) ?");
            String next = s.nextLine();
            int val = 0;

            try {
                val = Integer.parseInt(next);
            } catch (RuntimeException e) {
                if (next.equals("exit"))
                    return;

                System.err.println("Not a valid number");
                continue;
            }

            pw.println(username + " " + val);
        } else if (response.equals("login")) {
            System.out.println("What is your username?");
            String username = s.nextLine();

            if (username.equals("exit"))
                return;

            boolean didFind = false;
            Scanner scanner = new Scanner(new File("C:\\Users\\nisha\\IdeaProjects\\LeetCode\\src\\com\\company\\Accounts"));

            while (scanner.hasNextLine()) {
                String[] parts = scanner.nextLine().split(" ");

                if (parts[0].equals(username)) {
                    System.out.println("Your value is " + parts[1]);
                    didFind = true;
                    break;
                }
            }

            if (!didFind) {
                System.err.println("Your username was invalid");
                continue;
            }
        } else if (response.equals("exit")) {
            pw.close();
            return;
        } else {
            System.err.println("Invalid option");
            continue;
        }

        pw.close();
    }

我要添加的另一个功能是删除您的帐户。但是,我找不到从 PrintWriter 中删除某行而不删除整个文件内容的方法。我该怎么做呢?

我研究了一堆不同的网站,但它们都没有打开附加模式,因此不可能只删除几个字符。

标签: javaprintwriter

解决方案


推荐阅读