![](/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.