开发者

Write to disk file incorrect

开发者 https://www.devze.com 2023-02-15 23:05 出处:网络
I would like to write out the values of my array to a file.开发者_如何转开发 public void Write(String fileName) throws IOException

I would like to write out the values of my array to a file. 开发者_如何转开发

public void Write(String fileName) throws IOException
{

    PrintWriter outFile;
    outFile = new PrintWriter(new FileWriter(fileName));

    for(int K = 0 ; K < CurrentCount ; K++)
        outFile.println(List[K].toString());

    outFile.close();
}

The data entered into the file was: WeatherStation@1194a4e

The WeatherStation class has my constructor and get and set methods

 List[K] = new WeatherStation(Location, Temp, Title, Air, Pollen);

I was expecting all of the attributes above to get placed into the file.


If you expect that, then you will need to override toString for your WeatherStation class.

The default is a very simple one which outputs the type and a unique ID (not sure whether it's an address or hash off the top of my head).

Simply add a toString method which goes through the members off your class (that you want printed) and concatenate them into a string.

This link here has a good example on how to do this. You'd do something like:

@Override public String toString() {
    StringBuilder result = new StringBuilder();

    result.append (this.getClass().getName() + " {");
    result.append (" Location=[" + this.Location + "]");
    result.append (", Temp=[" + this.Temp + "]");
    // Other fields.
    result.append (", Pollen=[" + this.Pollen + "]");
    result.append (" }");

    return result.toString();
  }

It's untested and probably not the exact format you want, but it should be a good start.


You would need to override toString() in your WeatherStation class to produce the output you want.


Simplify your life!

  • a) There is no problem with initializing on declaration.
  • b) The simplified for-loop is - well - simplified.
  • c) If you don't pass a primitive or String to println, .toString () will be called automatically.

compare yourself:

public void Write(String fileName) throws IOException
{
    PrintWriter outFile = new PrintWriter (new FileWriter (fileName));
    for (WheatherStation ws : List)
        outFile.println (ws);
    outFile.close();
}

And - did anybody tell you to overwrite 'toString'? ;) I agree.

0

精彩评论

暂无评论...
验证码 换一张
取 消