2009-08-04 7 views
3

id number을 기반으로 한 텍스트 파일에서 한 줄을 지울 수있는 방법이 정말 흥미 롭습니다. 그러나이 방법을 모르겠습니다."studentId"를 기반으로 텍스트 파일에서 행을 제거하는 방법은 무엇입니까?

다음
1111111,John Smith<br/> 
7777777,Dave Smith 

내가 코드를 지금까지 가지고 무엇을 : 같은

students.txt 파일을 찾습니다


// class Student 
import java.io.*; 

public class Student implements Serializable
{
// 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; } }
// class EnrollmentController
import java.util.*; import java.io.*; 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(); /** * Constructor for objects of class EnrollmentController */ 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; } } } }
+0

하고, 질문의 수준, 당신이 적어도 노력을하지 않았다 가정 문제를 해결할 수 있습니다. 코드에 대한 귀하의 구체적인 의심과 무엇을 이미 시도했는지 게시하십시오. – OscarRyz

답변

6

당신은 원본 파일에서 읽을 수는, 임시 파일에 쓰기 만 지정된 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(); 
    } 
} 
+0

안녕하십니까, 해결책 주셔서 감사합니다.하지만 코드를 통해 설명해주십시오. Java에서 총 초보자입니다. 고마워요. –

+0

자, 가야 겠어.하지만 잘 돌아갈거야. java를 사용하여 쉼표로 분리 된 텍스트 파일을 읽고 쓰는 것에 관한 온라인 기사를보십시오. –

2

당신은 Stringsplit 방법을 사용할 수 있습니다. ","으로 분할 한 다음 제거하려는 ID의 색인 0을 확인하십시오. (즉,이 경우 아무것도 인쇄하지 마십시오.) 예제 코드를 제공 하겠지만 Java 컴파일러를 더 이상 설치하지 않았습니다.

1

아마도 모든 학생을 읽고 싶지만 ID를 기반으로 특정 학생을 쓰고 싶지는 않을 것입니다. 그것은 다음과 유사한 그래서 그래서이 경우에, 당신의 writeToStudentFile() 메소드를 수정 : 사용자가 제공 한 소스 코드를 기반으로

public void writeToStudentFile(int idToIgnore) 
{ 
    try{ 
     writer = new BufferedWriter(new FileWriter(studentFile, true)); 
     Iterator it = students.iterator(); 
     while (it.hasNext()) 
     { 
      Student s = (Student)it.next(); 
      if (s.getId() != idToIgnore) 
      { 
       writer.write(s.getId() + "," + s.getName() + "\n"); 
      } 
     } 
     writer.flush(); 
     writer.close(); 
    } 
    catch(IOException e){System.out.println(e);} 
} 
관련 문제