2014-12-15 2 views
-1

Привет, товарищи по стопке. У меня возник вопрос о Java, я должен поместить все объекты p1-p4 в файл с именем «personen.obj» и для p1, записать все данные в «persoon1.obj» и т. Д.Запись объекта в файл «Персоны.обь»

Вот код Я работаю с, он не включает компьютерный класс, потому что я думал, что это не обязательно.

Это включает некоторые строки на голландском языке, но каждый человек имеет toString с их данными. То, что должно случиться, состоит в том, что все тестры записываются в эти файлы.

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

Checkout ObjectOutputStream: http://www.javapractices.com/topic/TopicAction.do?Id=57. вы узнаете, как вы изучаете java, google - ваш друг, но вам нужно знать несколько ключевых слов для Google – 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; 
} 

Это также стоит знать о кодировках. Некоторые системы могут/будут писать текстовые файлы по-разному, чем другие, в большинстве случаев это не проблема, но это может быть потенциально.

я очень рекомендую дать некоторые из оракула Уроки чтения:

Кроме того, убедитесь, чтобы дать некоторые другие сайты для чтения, как большинство из них даст другой метод решения та же проблема, хотя и с разными плюсами и минусами.

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