• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 317
  • Last Modified:

How to write object data into text file

Hi,

I have 3 values which I want to write into a text file (.dat). The data is read from a Map object and also an array of Integer.
The code snippet is as follows:

  Pixel[] freqList = new Pixel[frequent];
  Iterator iter = data.iterator();
  int[] colValue = new int[frequent];
  int index = 0;
  while (iter.hasNext()){
    Map.Entry sortedEntries = (Map.Entry)iter.next();
    freqList[index] = (Pixel) sortedEntries.getKey();
    colValue[index] = freqList[index].getColourValue();
    textPanel.println(" (" +sortedEntries.getKey()+ ")\t\t" + colValue[index] + "\t\t" +sortedEntries.getValue());
    index++;
}
The three values I want to write are from sortedEntries.getKey(), sortedEntries.getValue() and colValue[index].
I have looked around but found nothing which can help me. Anyway, out of curiousity, do I need to use ObjectOutputStream?
Can anyone help me?

Many thanks.
0
hzinox
Asked:
hzinox
  • 8
  • 5
  • 3
4 Solutions
 
hzinoxAuthor Commented:
Thanks for your prompt respond. I am still learning Java and got lots to explore. If you could explain to me how I can do that or if you could direct me to a any related sources, I am mostly greatful. Thanks again.
0
 
objectsCommented:
Use the PrintWriter class

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.dat")));

It provides print methods to write various data types to the file

http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html

once done close file with close() method
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
hzinoxAuthor Commented:
Hi Object,

Had tried the PrintWriter and it does works for my sortedEntries.getKey() data. However, I noticed that the Printwriter cannot write data of type Integer array only Char[] and since my colValue[index] is of the former type, do I need to do something with it first? By the way, is there anyway I can write my data to my text file in such a way that looks like this
0
 
hzinoxAuthor Commented:
Sorry, accidentally posted the unfinished comment.... :-)

Hi Object,

Had tried the PrintWriter and it does works for my sortedEntries.getKey() data. However, I noticed that the Printwriter cannot write data of type Integer array only Char[] and since my colValue[index] is of the former type, do I need to do something with it first? By the way, is there anyway I can write my data in such a way that they will looks like the following in my text file?  

sortedEntries.getKey()      colValue[index]     sortedEntries.getValue()
      234,234,344                   1232342                      567

Thank you.
0
 
objectsCommented:
either add a toString() method to your Pixel class that outputs it as required


or call a different method to display it

    textPanel.println(" (" +sortedEntries.getKey().getText()+ ")\t\t" + colValue[index] + "\t\t" +sortedEntries.getValue());

you may need to use a loop to implement the toString()/getText() method to loop thru your array and display each value individually. A StringBuilder or StringBuffer can be used to build up the string.
0
 
CEHJCommented:
You can do something like


            PrintWriter out = new PrintWriter(new FileWriter("values.txt"));

.................................................

            out.printf("%-30s%-30s%-30s\n", "sortedEntries.getKey()", "colValue[index]",
                        "sortedEntries.getValue()");
            out.printf("%,d%28d%30d\n", p, c, v);
            out.close();
0
 
hzinoxAuthor Commented:
Hi Objects,

Have tried the toString() method but my colValue[index] still is not displayed it my .dat file.

Hi CEHJ,

Have tried yours too but probably the way I wrote was misleading. What I really want to write to the .dat file is just the data excluding the title i.e. "sortedEntries.getKey()", "colValue[index]","sortedEntries.getValue()". Sorry about this.

As at this moment I have successfully write both my sortedEntries.getKey() and sortedEntries.getValue() data into my dat file. However my data from the last loop is captured. I know what is the problem but I couldn't find how I can make my loop so that all data from each loop is captured in the .dat file.

Have tried so many ways including if (!file.exists), reading if the out file is not null etc.. but still I cannot get ot done.

Can any one help me here...so after so many do and undo... what I have is just the following

try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(
               "C:/Documents and Settings/hxp/Research writing/Reports/dataFile/rgbData.dat")),true);
        /*File file = new File ("C:/Documents and Settings/hxp/Research writing/Reports/dataFile/rgbData.dat");
        if (file.exists()) {*/
          while (iter.hasNext()) {
            Map.Entry sortedEntries = (Map.Entry) iter.next();
            freqList[index] = (Pixel) sortedEntries.getKey();
            colValue[index] = freqList[index].getColourValue();
            textPanel.println(" (" + sortedEntries.getKey() + ")\t\t" + sortedEntries.getValue());
            out.println(sortedEntries.getKey() + "\t\t" + sortedEntries.getValue());
            index++;
          }
          out.println(" ");
          out.close();
        }
catch (Exception e) {}
      }

Many thanks.
0
 
hzinoxAuthor Commented:
Hi,

Can anyone help me with the problem posted earlier? BTW, I have increase the points :-). Thanks.
0
 
objectsCommented:
> my colValue[index] still is not displayed it my .dat file.

its not in your println() call any more :)
0
 
hzinoxAuthor Commented:
Hi,

Yes, I have taken it out from my problem as for this moment. Oooo gosh... I think I might have wrongly address my main concern now :) sorry. Actually, I have 8 iterations in my loop. As at now, I only able to write into the .dat file my data from the last iteration in the file which I knew exactly why. This is because the current data is being overwritten by the data of the next iteration since I am only using a single .dat file.

Out of nowhere suddenly I am thinking, can I have my data in each iteration to be written in different .dat file. For example, can the data from the 1st iteration written into Data1.dat and data from the 2nd iteration into Data2.dat and so on. This is because I just realise that I need my plotting software to plot the whole iterations' data into a single graph so I need to have my data in different files.

Sorry for my misinterpretation of my problem there. Any help is very much appreciated.

 
0
 
objectsCommented:
> can I have my data in each iteration to be written in different .dat file.

sure, open each file inside your iteration loop using the iteration number to construct the filename
eg.  filename = "Data"+inumber+".dat";
0
 
hzinoxAuthor Commented:
Hi objects,

Gladly to tell you, I have solved the problem. I have got my data in each iteration written into a different .dat file. Many thanks : )

Can I just ask about the "> my colValue[index] still is not displayed it my .dat file."?

I found out that the PrintWriter class does not have method which accept to write an array of integer. Since my colValue[index] is actually an array of integer, I cannot have them to be written into the .dat file. I have actually do it this way

strColourVal[index] =Integer.toString(colValue[index]);
out.print(strColourVal[index]);

but I have an error, does it have anything to do with the PrintWriter also does not specifically have method to write an array of String? I know it can accept String...

0
 
objectsCommented:
To write an array of int's you'll need to use a loop to display each arrayu element individually.
0
 
hzinoxAuthor Commented:
Hi Objects,

Don't know why it does not work the first time I've tried the same way you've suggested but then it works just fine now. Thanks : ) !
0
 
CEHJCommented:
:-)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 8
  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now