2013-10-14 2 views
0

헤더에서 매우 명확하게 찾고있는 내용을 언급했습니다. 내가 필요한 모든 지침으로 수정하려고하는 코드를 제공했습니다. 이 순간에 내가 염려하는 유일한 것은 독자가이 과제에서 규정 한대로 모든 비용을 감축하는 것입니다. 당신이 코드에 사용 된 모든 독자를 제거하고 파일로 교체 할 경우File/ObjectInputStreams 만 사용하여 코드에서 독자 제거

import java.io.File; 
import java.io.FileWriter; 
import java.io.FileReader; 
import java.io.BufferedReader; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.Vector; 
import java.util.Iterator; 


public class QuestionManager { 
    String baseDirectory; 

    public QuestionManager(String baseDirectory) { 
     // Store the name of the base directory 
     // and create that directory if it does not exist 
     this.baseDirectory = baseDirectory; 
     File dir = new File(baseDirectory); 
     if (!dir.exists()) 
       dir.mkdir(); 
    } 

    public String add(String category, Question q) { 
     // Get the vector of questions from a category file 
     File f = new File(category); 
     f.createNewFile(); 
     Vector<Question> Q = new Vector<Question>(); 
     BufferedReader reader = new BufferedReader(new FileReader(f)); 
     String line = null; 
     while((line = reader.readLine())!= null) { 
      Q.add(Question)line); 
     } 
     // Add the question object to the vector 
     Q.add(q); 
     // Save the vector back to the category file 
     Iterator i = new Iterator<Question>(Q); 
     FileWriter w = new FileWriter(f); 
     while(i.hasNext()) { 
      w.write((int)(i.next())); 
     } 
     w.flush(); 
     w.close(); 
     // Return the result of the save operation 
     return Q; 
    } 

    public Question get(String category, int num) { 
     // Get the vector of questions from a category file 
     Vector<Question> questions = getCategoryFile(category); 
     // Check that the index number is valid (between 0 and the vector size - 1) 
     if (num >= 0 && num < questions.size()) { 
     // If valid, return the question object 
      return questions.elementAt(num); 
     } 
     else { 
      // else return null 
      return null; 
     } 
    } 

    public String update(String category, Question q, int num) { 
     // Get the vector of questions from a category file 
     Vector<Question> questions = getCategoryFile(category); 
     // String variable to hold the result of save operation 
     String result; 
     // Check that the index number is valid (between 0 and the vector size - 1) 
     if (num >= 0 && num < questions.size()) { 
     // If valid, replace the question at that index in the vector with the new 
      questions.set(num, q); 
      // question object, then save the file and return the result of the 
      // save operation 
      result = saveFile (category, questions); 
      return result; 
     } 
     else { 
      // If index is invalid return a string indicating that. 
      return "Invalid Index!"; 
     }  
    } 

    private String saveFile(String category, Vector<Question> questions) { 
     // Create the file object: 
      // category is a file name inside the base directory 
     File F = new File(category); 
     // Inside a try block, 
     try { 
      // Create FileOutputStream for the category file 
      FileOutputStream saveFile = new FileOutputStream(F, true); 
      // Create ObjectOutputStream for the category file 
      ObjectOutputStream save = new ObjectOutputStream(saveFile); 
      // Write the vector to the file 
      save.writeObject(questions); 
      // Flush the object stream, the close both streams 
      save.flush(); 
      save.close(); 
      saveFile.close(); 
      // Return a string indicating success 
      return "Success"; 
     } 
     // Catch blocks: 
     catch (Exception E) { 
      // Return an error string indicating the problem 
      return "Error in writing to the file " + category; 
     } 
    } 

    private Vector<Question> getCategoryFile(String category) { 
     //Create the file object: 
      // category is a file name inside the base directory 
     File F = new File(category); 
     // Create an empty vector of questions 
     Vector<Question> questionVector; 
     // Inside a try block, 
     try { 
      // Create FileInputStream for the category file 
      FileInputStream saveFile = new FileInputStream(F); 
      // Create ObjectInputStream for the category file 
      ObjectInputStream save = new ObjectInputStream(saveFile); 
      // Read the vector from the file 
      questionVector = (Vector<Question>) save.readObject(); 
      // Close both streams 
      save.close(); 
      saveFile.close(); 
     } 
     // Catch blocks: 
     catch (Exception E) { 
      E.printStackTrace(); 
      // Create an empty vector of questions 
      questionVector = new Vector<Question>(); 
     } 
     // Return the vector 
     return questionVector; 
    } 
} 
+0

여기서'f.createNewFile()'을 호출 할 필요가 없습니다. 어쨌든'new FileWriter()'는 그렇게합니다. 'close()'의 직전에'flush()'를 호출 할 필요가 없습니다. – EJP

답변

-1

/ObjectInputStream를 한 후 나는 그것이 가능하다고 생각하지 않습니다. 어쨌든 스트림을 읽으려면 독자가 있어야합니다. 나는 당신이 독자 또는 writters없이 스트림을 조작 할 수 없습니다 알다시피

+0

물론 독자 나 작성자없이 스트림을 조작 할 수 있습니다. 말도 안되는 소리. – EJP

0

코드는 심지어 당신의 질문은 이미 이론에 불과하게하는, 컴파일되지 않으며, 혹시 StringQuestion.

으로 캐스팅하려고하는 방법이 없습니다

그러나이 동일한 조항에 따라 행을 읽어야 할 의무가 있으면 DataInputStream.readLine(),으로 변경해야하며 이는 규정과 상충 될 수 있습니다. 이는 자기 모순이 될 수 있습니다. 스트림 API를 사용하여 다른 모든 작업을 수행 할 수 있습니다.

+0

코드가 컴파일되지 않습니다. 왜냐하면 이것은 3 개의 클래스 중 오직 1 개이고 주 코드가 아니기 때문에 컴파일되지 않습니다. 전 이사하기 전에이 섹션을 수정하려고했습니다. – Ryel

+0

(a) 구문 오류가있어서 (b)'Question '에'String'을 캐스팅 할 수 없으므로 코드가 컴파일되지 않습니다. – EJP