![](/img/trans.png)
[英]How to write to a txt file “using the keyboard and PrintWriter Class ” created in java
[英]How to edit a txt file using PrintWriter?
我有以下java文件,它將學生數據(學生編號及其姓氏)存儲在txt文件中:
import java.util.*;
import java.io.*;
public class Students {
static Student[] studentArray = new Student[100];
static int currentStudents = 0;
Scanner console = new Scanner(System.in);
File log = new File("log.txt");
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(log, true)));
Scanner input = new Scanner(log);
public static void main(String[] args) {
String logNo;
String logSurname;
if(!(input.hasNextLine())) {
System.out.println("No student data has been loaded.")
}
while(input.hasNextLine()) {
logNo = input.next();
logSurname = input.next();
addStudent(logNo, logSurname);
input.nextLine();
}
String number;
String surname;
System.out.println("Please input details:");
System.out.printf("\n");
System.out.println("Student number: ");
number = console.nextLine();
System.out.println("Student surname: ");
surname = console.nextLine();
output.println(number+"\t"+surname);
addStudent(number, surname);
editSurname();
output.close();
}
public static void addStudent(String number, String surname) {
studentArray[currentStudents] = new Student(number, surname);
}
public static void editSurname() {
String newSurname;
System.out.println("Please input student number:");
// find student with inputted student number
System.out.println("Please enter new surname");
// set surname to another using Student method
}
}
打開時,代碼讀入.txt文件中的任何文本,並根據需要構造Student
對象,以便每次運行代碼時系統的狀態都會持續存在。
但是,當我調用editSurname()
函數時,我很難找到使用PrintWriter
編輯.txt文件的方法。 我如何將學生與特定學生編號隔離,然后編輯所需的字段?
使用csv文件而不是txt文件。 使用OpenCSV處理記錄。
要么
要編輯學生記錄,您需要先讀取內存中的所有記錄。 創建一個學生對象數組以保存所有記錄。 對對象執行二進制搜索並修改它們。
為什么不使用數據庫概念,可以使用數據庫輕松完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.