2012-08-04 4 views
2

Я использую RandomAccessFile для создания базы данных в текстовый файл. В основном я создал обычный магазин, используя ArrayList, и теперь мне нужно выводить содержимое магазина с помощью RandomAccessFile. Но я зациклился на том, как получить метод randomAccessFile, чтобы взять магазин ученика. Вот мой код:Можно ли распечатать объект Student с помощью RandomAccessFile?

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.io.RandomAccessFile; 


public class MainApp 
{ 
    private RandomAccessFile File; 

    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(); 




     //Create a file object. 
     File contactDetailsFile = new File("StudentDetails.txt"); 
     //Open a buffered output stream to allow write to file operations. 
     PrintWriter out = new PrintWriter(
          new BufferedWriter(
          new FileWriter(contactDetailsFile))); 

     out.println(a); 
     out.println(b); 
     out.println(c); 
     out.println(d); 
     out.println(e); 
     out.close(); 

     BufferedReader in = new BufferedReader(
          new FileReader(contactDetailsFile)); 

     String line = in.readLine(); 
     System.out.println(line); 

     out.close(); 

    } 
/** 
* @param args the command line arguments 
*/ 
public void RandomAccessFile(String filename) 
{ 

    RandomAccessFile randomAccessFile = null; 
    try { 

     //Declare variables that we're going to write 
     String line1 = "First line\n"; 
     String line2 = "Second line\n"; 

     //Create RandomAccessFile instance with read/write permissions 
     randomAccessFile = new RandomAccessFile(filename, "rw"); 

     //Write two lines to the file 
     randomAccessFile.writeBytes(line1); 
     randomAccessFile.writeBytes(line2); 

     //Place the file pointer at the end of the first line 
     randomAccessFile.seek(line1.length()); 

     //Declare a buffer with the same length as the second line 
     byte[] buffer = new byte[line2.length()]; 

     //Read data from the file 
     randomAccessFile.read(buffer); 

     //Print out the buffer contents 
     System.out.println(new String(buffer)); 

    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     try { 

      if (randomAccessFile != null) 
       randomAccessFile.close(); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

} 

} 
+0

Это домашнее задание? – Reimeus

+0

Да, извините, я забыл тег, который сейчас отредактирую. – Pendo826

+0

Это намного проще с ObjectInputStream, имеет ли RandomAccessFile определенное требование? – Reimeus

ответ

3

Одним словом, да.

Вам снова придется повторно выполнить часть части описания этого решения. Вы должны прочитать объекты обратно так же, как вы их написали.

Из этого example вы можете увидеть, как каждый член написан с использованием объекта RandomAccessFile.

Я предлагаю вам сделать метод чтения из примера возвратом нового объекта Student.

 Смежные вопросы

  • Нет связанных вопросов^_^