3 java
我真的很有兴趣有一个方法可以从文本文件中删除一行基于id number,但我不知道如何实现这一点.
该students.txt文件看起来像:
1111111,John Smith<br/>
7777777,Dave Smith
Run Code Online (Sandbox Code Playgroud)
以下是我到目前为止的代码: 公共班学生:
public class Student {
// instance variables
private int studentId;
private String name;
/**
* Constructor for objects of class Student
*/
public Student(int id, String name) {
this.name = name;
studentId = id;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public void setId(int newId) {
studentId = newId;
}
public int getId() {
return studentId;
}
}
Run Code Online (Sandbox Code Playgroud)
公共类EnrollmentController:
public class EnrollmentController {
private Student theStudent;
private BufferedWriter writer;
private BufferedReader reader;
private final File studentFile = new File("students.txt");
private ArrayList students = new ArrayList();
public EnrollmentController() {
readFromStudentFile();
}
public ArrayList getStudents() {
return students;
}
public void addStudent(int id, String name) {
students.add(new Student(id, name));
}
public void printClassList(String courseId) {
}
public void writeToStudentFile(int id, String name) {
try {
writer = new BufferedWriter(new FileWriter(studentFile, true));
writer.write(id + "," + name + "\n");
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void readFromStudentFile() {
students = new ArrayList();
try {
reader = new BufferedReader(new FileReader(studentFile));
String line = reader.readLine();
while (line != null) {
String[] record = line.split(",");
int id = Integer.parseInt(record[0]);
Student s = new Student(id, record[1]);
students.add(s);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
System.out.println(e);
}
}
public Student findStudent(int id) {
boolean found = false;
Iterator it = students.iterator();
while (it.hasNext() && !found) {
Student s = (Student) it.next();
if (s.getId() == id) {
found = true;
return s;
}
}
return null;
}
{
boolean found = false;
{
{
found = true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从原始文件中读取,仅将那些与指定ID不匹配的记录写入临时文件,然后在最后用新临时文件替换原始文件.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
public class Demo{
public static void main(String[] argv)
throws Exception{
Writer output = new BufferedWriter(new FileWriter("fixed.txt"));
BufferedReader freader =
new BufferedReader(new FileReader("orinal.txt"));
String s;
while ((s=freader.readLine())!=null){
String tokens[] = s.split(",");
String id = f[0];
String name = f[1];
// check against the ID or ID's you don't want. If the current ID is not the one
// you don't want then write it to the output file
if (!id.equals("00001") {
output.write(s + "\n");
}
}
freader.close();
output.close();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3925 次 |
| 最近记录: |