2014-12-15 4 views
-1

안녕하세요, 동료 Stackoverflowers. Java에 관한 질문이 있었는데 모든 개체 p1 - p4를 "personen.obj"라는 파일에 넣고 p1의 경우 모든 데이터를 "persoon1.obj"등으로 작성해야합니다."Persons.obj"파일에 개체 쓰기

코드는 다음과 같습니다. 나는 그것이 필자가 필요하지 않다고 생각했기 때문에 Computer 클래스를 포함하지 않았다.

여기에는 네덜란드어로 된 일부 문자열이 포함되어 있지만 모든 사람에게는 데이터가있는 toString이 있습니다. 무슨 일이 일어날 예정이다 모든 toStrings 그 파일에 기록됩니다.

import java.util.Calendar; 

public class Main { 
public static void main(String[] args) { 
    int huidigJaar = Calendar.getInstance().get(Calendar.YEAR); 
    int aanschafJaarC1 = huidigJaar - 4; // c1 is 4 jaar oud 
    int aanschafJaarC2 = huidigJaar - 3; // c2 is 3 jaar oud 
    Persoon p1 = new Persoon("Eric", 20000); 
    Persoon p2 = new Persoon("Hans", 60000); 
    Persoon p3 = new Persoon("Willem-Alexander", 8500000); 
    Computer c1 = new Computer("Medion", 2000, aanschafJaarC1, "Super"); 
    Computer c2 = new Computer("Dell", 1500, aanschafJaarC2, "Home"); 
    if (p1.koop(c1)) { 
     System.out.println("Deze koper bezit nu nog " + p1.getBudget()); 
    } 
    if (p1.koop(c1)) { 
     System.out.println("Deze koper bezit nu nog " + p1.getBudget()); 
    } 
    if (p2.koop(c1)) { 
     System.out.println("Deze koper bezit nu nog " + p2.getBudget()); 
    } 
    if (p2.koop(c2)) { 
     System.out.println("Deze koper bezit nu nog " + p2.getBudget()); 
    } 
    if (p3.koop(new Computer("Dell", 1500, aanschafJaarC2, "Home"))) { 
     System.out.println("Deze koper bezit nu nog " + p3.getBudget()); 
    } 
    if (p3.koop(c2)) { 
     System.out.println("Deze koper bezit nu nog " + p3.getBudget()); 
    } 
    System.out.println("\n" + p1); 
    System.out.println(p2); 
    System.out.println(p3); 
    if (p1.verkoop(c1, p3)) { 
     System.out.println("Deze verkoper bezit nu nog " + p1.getBudget()); 
    } 
    if (p2.verkoop(c1, p3)) { 
     System.out.println("Deze verkoper bezit nu nog " + p2.getBudget()); 
    } 
    if (p2.verkoop(c2, p1)) { 
     System.out.println("Deze verkoper bezit nu nog " + p2.getBudget()); 
    } 
    System.out.println("\n" + p1); 
    System.out.println(p2); 
    System.out.println(p3); 
} 
} 
+0

체크 아웃 ObjectOutputStream : http://www.javapractices.com/topic/TopicAction.do?Id=57. 당신은 자바를 배우는 동안 당신이 찾을거야, 구글은 당신의 친구지만, 구글에 많은 키워드를 알 필요가있다. – Joeblade

답변

0

단순히 파일에 적은 수의 문자열을 쓰려면 "PrintWriter"클래스를 사용하는 것이 좋습니다. 표준 Writer를 중심으로 랩핑되며 기본 데이터 형식과 일부 개체를 지정된 "Writer"(이 경우 FileWriter)에 쓸 수 있습니다.

물론 이것은 파일에 기록하는 유일한 방법이 아니며 가장 좋은 방법이기도합니다.

메모리에서 일부 코드를 빨리 작성했지만 테스트하지는 않았지만 제대로 작동하는지 확신합니다.

/** 
* This method will write an array of strings to the given file. 
* If the append flag is set to true, the new data will be added to the end of the file. 
* 
* Note: 
* This is not only nor the best way to write to a file. 
* 
* @param filename - The path to the file you want to write to. 
* @param data - The Strings you want to write to the file. 
* @param append - Should the new data be added to the end of the file? 
* @return If the write operation succeeded. 
*/ 
public static boolean writeStringsToFile(String filename, String[] data, boolean append) { 
    boolean resultFlag = true; 

    // The file class represents a file on a disk and provides some useful methods 
    File file = new File(filename); 
    //PrintWriter is used to write various data types to a given writer. 
    PrintWriter printWriter = null; 

    try { 
     //This method will create an empty file, if there's not already one. 
     //Will throw an IOException if it experiences an error creating the file. 
     file.createNewFile(); 

     //A PrintWriter needs some kind of writer to output to, we'll use a FileWriter. 
     //FileWriter is used for writing to files. 
     //Will throw an IOException if the file doesn't exist (It should exist though) 
     printWriter = new PrintWriter(new FileWriter(file, append)); 

     for(int i = 0; i < data.length; i++) { 
      //Write the strings to the file, each on a new line. 
      printWriter.println(data[i]); 
     } 

    } catch (IOException e) { 
     //Uh oh. There was an error writing to the disk! 
     e.printStackTrace(); 

     //We couldn't write to the disk, make sure we return false to let the caller know. 
     resultFlag = false; 
    } finally { 
     //First check that we managed to create a PrintWriter before we try to close it. 
     if (printWriter!=null) 
      printWriter.close(); //Release the file from use. 
    } 

    return resultFlag; 
} 

인코딩을 인식 할 필요가 있습니다. 특정 시스템에서는 다른 방법과 다른 방법으로 텍스트 파일을 쓰거나 쓸 수 있지만, 대부분의 경우에는 문제가 아니지만 잠재적으로 그렇게 할 수 있습니다.

나는 매우 높은 오라클의 일부를주는 것이 좋습니다

읽기 자습서 :

이 또한 대부분을 해결하기 위해 다른 방법을 줄 것 같은 읽고 다른 사이트를 제공해야합니다을 서로 다른 장단점이 있지만 같은 문제입니다.