我正在編寫我的編程介紹項目。該程序應該使用文本文件作爲數據庫來存儲名字,姓氏和電話號碼。該程序需要能夠處理文本文件上的數據。我需要幫助對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對象執行其他操作 –