java - 如何使用 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 中删除某行而不删除整个文件内容的方法。我该怎么做呢?
我研究了一堆不同的网站,但它们都没有打开附加模式,因此不可能只删除几个字符。
解决方案
推荐阅读
- angular - 电容相机预览的预览覆盖了动作按钮
- python - 按分组行获取唯一值
- python - 带有for循环数据的seaborn线图,并通过轴值参数更改线条颜色
- python - qgis插件中未阻止执行方法
- spring-boot - 没有使用spring boot应用程序登录外部tomcat
- sql - SQL我如何从日期时间转换为总小时数?
- python - 请求:在 python 发布请求中发送有效负载时出错
- asp.net-core - “Microsoft.Extensions.Caching.Memory”的 Asp.net Core、MemoryCache 和 CacheExtensions 是否是线程安全类型?
- hadoop - 如何选择映射器和减速器计数?
- php - 如何在 TypeORM 中获取按类别 ID 分组的产品?