2012-08-07 3 views
0

안녕하세요 저는 ArrayList 상점 학생을위한 add 메소드에 붙어있어 학생 상점을 randomAccessFile을 사용하여 텍스트 파일에 씁니다. 그래서 나는 학생을 가게에 추가하고 그 파일에 쓸 수 있어야한다. 아무도 내가 이것을 할 수있는 방법을 제안 할 수 있습니까? 나는 학생을 아무 문제없이 가게에 추가 할 수 있지만 실제 문제는 정적 배열을 사용하여 파일에 학생을 쓴다는 것이고 사용자가 정적 배열에 새 직원을 추가하도록하는 방법에 대해 확신하지 못한다는 것입니다.RandomAccessFile에 대한 메소드 추가

import java.io.IOException; 
import java.io.RandomAccessFile; 
public class MainApp 
{ 

    public static void main(String[] args) throws Exception 
    { 
     new MainApp().start(); 

    } 
    public void start()throws Exception 
    { 
     StudentStore details = new StudentStore(); 
     Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "[email protected]"); 
     Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "[email protected]"); 
     Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "[email protected]"); 
     Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "[email protected]"); 
     Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "[email protected]"); 
     details.add(a); 
     details.add(b); 
     details.add(c); 
     details.add(d); 
     details.add(e); 
     //details.print(); 


     RandomAccessFile file = new RandomAccessFile("ContactDetails.txt","rw"); 
     //getBytes() returns an array of bytes. 
     //Because i have put the store in a static Array.(I done this because i could find no other 
     //Simple way to write a Student Object.) 
     //None of the methods of the RandomAccessFile write class worked with this. 
     Student[] students = {a,b,c,d,e}; 
     details.write(students, file); 
     details.readAll(file); 



     file.close(); 


    } 


} 

StudentStore

에게
//--------------------------------------------------------------------------- 
//Imports. 
//--------------------------------------------------------------------------- 
import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.util.ArrayList; 
import java.util.List; 
//--------------------------------------------------------------------------- 

public class StudentStore 
{ 
//--------------------------------------------------------------------------- 
//ArrayList declaration. 
//--------------------------------------------------------------------------- 
    List<Student> students = new ArrayList<Student>(); 
//--------------------------------------------------------------------------- 
//Name:   Add method. 
//Description: Adds a student to the ArrayList. 
//--------------------------------------------------------------------------- 
    public void add(Student student) 
    { 
     students.add(student); 
    } 
//--------------------------------------------------------------------------- 
//Name:   DeleteAll method. 
//Description: Delete's everything in the ArrayList. 
    //--------------------------------------------------------------------------- 
    public void deleteAll() 
    { 
      students.clear(); 
    } 
//--------------------------------------------------------------------------- 
//Name:   Print method. 
//Description: Prints out the contents of the ArrayList. 
//--------------------------------------------------------------------------- 
    public void print() 
    { 
     for (int i = 0; i < students.size(); i++) 
     { 
      Student a = students.get(i); 
      System.out.println(a.toString()); 
     } 
    } 
    public int size() 
    { 
     return (students == null) ? 0 : students.size(); 
    } 
    public void write(Student[] students, RandomAccessFile file) throws IOException 
    { 
     for (int i = 0; i < students.length; i++) 
     { 
     byte[] bytes = students[i].toString().getBytes(); 
     for(byte byteWrite : bytes) 
     { 
      file.writeByte(byteWrite); 
     } 
     } 

    } 
    public void readAll(RandomAccessFile file) throws IOException 
    { 
     final int Record_Length = 30; 
     int recordNumber = 0; 
     file.seek((recordNumber) * Record_Length); 

     String code =""; 
     for(int i = 0; i < 30; i++) 
     { 
     code += file.readLine() + "\n"; 
     } 
     System.out.println(code); 
    } 

} 

MainApp : 여기

내 코드가, getter 및 setter와 생성자의 구축되어 있기 때문에 나는 학생 클래스를 보여 havent 한 toString과 나는 그것을 업로드하는 것을 느끼지 못했지만 필요할 경우 나는 기꺼이 그것을 할 것이다.

+1

write 메소드에서 매개 변수로 배열을 전달하는 대신 ArrayList를 반복해야합니까? –

+0

Im은 매개 변수로 배열을 전달하므로 mainApp의 메소드를 많이 사용하지 않고도 main의 맨 아래에 메서드를 사용할 수 있습니다. – Pendo826

+1

아마 배열 대신 정적'List'를 사용할 것입니다. 배열을 복사하는 메소드와'System.copyArray '를 가지고 있기 때문에 당신은'Arrays' 클래스 (http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html)를 볼 수 있습니다. 'http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int), 솔직히 말해서, ArrayList는 당신을 위해 이것을 수행합니다. – MadProgrammer

답변

1

개인적으로 파일에 쓰기 방법을 사용하기 위해 별도의 배열을 만드는 대신 파일에 arraylist를 작성합니다. 이것은 또한 귀하의 주요 방법을 단순화합니다.

StudentStore details = new StudentStore(); 
details.add(new Student("Becky O'Brien", "DKIT26", "0876126944", "[email protected]")); 
// add more students 
details.write(new RandomAccessFile("ContactDetails.txt","rw")); 

당신은 또한 그것을 더 단순화하고 바로 쓰기 방법에 대한 유일한 매개 변수는 파일 이름이 될 수 : 당신은 좋은 예를 들어이 같은 here

따라서, 기본이 보일 것이다 무언가를 볼 수 있습니다.

+0

배열을 사용하여 파일을 작성하는 데 문제가 발생했습니다. – Pendo826