我正在编写我的编程介绍项目。该程序应该使用文本文件作为数据库来存储名字,姓氏和电话号码。该程序需要能够处理文本文件上的数据。我需要帮助对java中的文本文件进行更改
这里是我的全部代码至今:
import java.util.*;
import java.io.*;
import java.lang.*;
import java.nio.*;
public class Project
{
private static Scanner input;
private static Formatter x;
public static void main(String[] args)
{
String choice = "";
Scanner userInput = new Scanner(System.in);
System.out.printf("Please choose one of the following commands:%nL (Listing), I (insert), S (search), D (delete)%nM (modify), W (write), Q (quit with saving)");
loop: while (choice != "Q") {
System.out.printf("%nEnter your Command: ");
choice = userInput.nextLine();
switch (choice)
{
case "L":
Listing();
break;
case "I":
Insert();
break;
case "S":
break;
case "D":
break;
case "M":
break;
case "W":
break;
case "Q":
break loop;
} // end switch statement
} // end while loop
} // end method main
public static void Listing() // List records from MiniDB.txt file
{
try {
File file = new File("MiniDB.txt");
input = new Scanner(file);
}
catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
if (input.hasNext()) { // If there are records in the file print them, else print none found
while (input.hasNext()) // while there is more to read
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
System.out.printf("%-13s%-13s%s%n", firstName + ",", lastName, phoneNumber); }
}
else {
System.out.printf("No records found");
}
} // end method Listing
public static void Insert() // insert a record
{
try {
String file = "MiniDB.txt";
input = new Scanner(System.in);
PrintWriter outputStream = new PrintWriter(new FileWriter(file, true));
System.out.printf("Last Name: ");
String lastName = input.next();
System.out.printf("%nFirst Name: ");
String firstName = input.next();
System.out.printf("%nTelephone Number: ");
String phoneNumber = input.next();
outputStream.printf("%n%s %s %s", firstName, lastName, phoneNumber);
outputStream.close();
System.out.printf("%nDone.");
}
catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
} // end method Insert
public static void Search(); // search a record
{
}
} // end class Project
我需要什么是了解如何创建“写”命令帮助。目前,我的代码会自动对文本文件进行更改,但我只需要在输入W时完成更改。我一直在阅读这篇文章,而且我完全陷入困境。我需要重写我的东西吗?
我在考虑对temp.txt文件进行所有更改,然后如果输入W,则重命名temp.txt MiniDB.txt并覆盖该文件。然后我需要删除temp.txt文件。我觉得应该有一个更简单的方法?
您可以使用相同的json对象执行其他操作 –