Java Forum / First Aid / November 2007
write read string data
bH - 20 Nov 2007 15:02 GMT Hi All,
I am attempting to write data into a file and read it back again.
The error occurs with reading the data file back, or so it would appear as the current output of that data is merely a column of null.
Your help is appreciated. bH
import java.io.*;
public class Example4withIO { String[][] tmp_array = new String [5][5] ;
public static void main(String[] args) { new Example4withIO(); } public Example4withIO() { // final String[] names = {"First Name", // "Last Name", "Favorite Color", // "Favorite Number", "Vegetarian"}; final Object[][] data = { {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE}, {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE}, {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE}, {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE}, {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE}, }; try { FileOutputStream f_out = new FileOutputStream ("C:\\myarray.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject(data); obj_out.flush(); obj_out.close(); } catch (IOException e) { System.out.println("error obj_out"); } // end saving data // attempting to recover the data try { BufferedReader obj_in = new BufferedReader(new FileReader ("C:\\myarray.data")); tmp_array.equals (obj_in); obj_in.close(); } catch (Exception eerr){ System.out.println("error getting in"); } for(int ib=0;ib<5;ib++) { for(int cb=0;cb<5;cb++) { System.out.println(tmp_array[ib][cb]); } }//end recover of data } }
Patricia Shanahan - 20 Nov 2007 16:07 GMT > Hi All, > [quoted text clipped - 4 lines] > or so it would appear as the current output of that > data is merely a column of null. ...
> // attempting to recover the data > try { [quoted text clipped - 4 lines] > obj_in.close(); > } I don't see where you actually read any data. You open the input as a BufferedReader, test whether an array is equal to the BufferedReader object (it isn't), ignore the result of the test, and close the input.
Having written the data using ObjectOutputStream and its writeObject method, you should read it using ObjectInputStream and its readObject method.
Patricia
Lew - 21 Nov 2007 01:19 GMT bH wrote:
>> I am attempting to write data into a file and read it >> back again. [quoted text clipped - 11 lines] >> obj_in.close(); >> }
> I don't see where you actually read any data. You open the input as a > BufferedReader, test whether an array is equal to the BufferedReader [quoted text clipped - 3 lines] > method, you should read it using ObjectInputStream and its readObject > method. Conversely, if you want to read from a FileReader (or FileInputStream), then write to a FileWriter (FileOutputStream).
Serialization (the storage of objects via ObjectXxxStreams) is a dicey subject and requires great care.
Also, do NOT do all this work in the constructor. Use the constructor only to construct the object. Do all real work in other methods, called from an instance of the object that was created in main().
 Signature Lew
bH - 21 Nov 2007 02:34 GMT > bH wrote: > >> I am attempting to write data into a file and read it [quoted text clipped - 34 lines] > > - Show quoted text - Hi All,
I am frustrated,
I have tried your suggesstions and see nothing that looks like the original data.
Your recommendations have, in my opinion have been inconsistant.
Why?
bH
Patricia Shanahan - 21 Nov 2007 02:47 GMT >> bH wrote: >>>> I am attempting to write data into a file and read it [quoted text clipped - 42 lines] > > Why? The advice is inconsistent because there are several good solutions to the problem. Also, we varied in how much extra advice we gave. For example, I didn't point out the undesirability of doing so much work in the constructor, but agree with that comment.
The most basic choice you need to make is between continuing to use ObjectStreamWriter, writing out serialized data, or switching to managing separating the strings yourself.
I suggest making any choice of which solution to attempt, and then post the latest version of your code.
Patricia
Hendrik Maryns - 20 Nov 2007 16:12 GMT bH schreef:
> Hi All, > [quoted text clipped - 4 lines] > or so it would appear as the current output of that > data is merely a column of null.
> import java.io.*; > [quoted text clipped - 20 lines] > Boolean.FALSE}, > }; In a more advanced application, you would create a class Person which has these things as attributes, but I understand that this is only an exercise.
> try { > FileOutputStream f_out = new FileOutputStream > ("C:\\myarray.data"); > ObjectOutputStream obj_out = > new ObjectOutputStream (f_out); Java naming conventions[1] would require you to write that as fOut, objOut. Also, consider using more descriptive names.
> obj_out.writeObject(data); > obj_out.flush(); [quoted text clipped - 3 lines] > { > System.out.println("error obj_out"); You might want to e.printStackTrace().
> } > // end saving data [quoted text clipped - 5 lines] > tmp_array.equals (obj_in); > obj_in.close(); You never actually read from the BufferedReader. equals is just a method to compare objects, see the Javadoc[2].
What you need is ObjectInputStream[3] and its readObject() method.
HTH, H.
[1] http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html [2] <http://72.5.124.55/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)> [3] http://72.5.124.55/javase/6/docs/api/java/io/ObjectInputStream.html
 Signature Hendrik Maryns http://tcl.sfs.uni-tuebingen.de/~hendrik/ ================== http://aouw.org Ask smart questions, get good answers: http://www.catb.org/~esr/faqs/smart-questions.html
Roedy Green - 21 Nov 2007 04:09 GMT >I am attempting to write data into a file and read it >back again. You have to read back with the same technique you write out with.
e.g. write objects / read objects. write binary / read binary write encoded chars / read encoded chars
See http://mindprod.com/applet/fileio.html for sample code to do it various ways.
You might do it each way and examine the file with a hex viewer to understand the different formats.
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
bH - 21 Nov 2007 04:15 GMT > >I am attempting to write data into a file and read it > >back again. [quoted text clipped - 13 lines] > Roedy Green Canadian Mind Products > The Java Glossaryhttp://mindprod.com Hi All.
I am not sure, at this point, if this is what was expected.
bH
import java.io.*;
public class Example4withIO {
public static void main(String[] args) { Example4withIO example4withIO = new Example4withIO(); GetData getData1 = new GetData(); } public Example4withIO() { System.out.println("inside Example4withIO"); // final String[] names = {"First Name", // "Last Name", "Favorite Color", // "Favorite Number", "Vegetarian"}; final Object[][] data = { {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE}, {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE}, {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE}, {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE}, {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE}, }; try { FileOutputStream fileOut = new FileOutputStream("C:\\myarray.data"); ObjectOutputStream objOutStream = new ObjectOutputStream (fileOut); objOutStream.writeObject(data); objOutStream.flush(); objOutStream.close(); } catch (IOException e) { System.out.println("error getting data"); } } }
import javax.swing.*; import java.io.*;
public class GetData extends JPanel {
String tempStrng = new String();
public GetData () { System.out.println("inside GetData"); try { FileInputStream fileIn = new FileInputStream("C:\\myarray.data"); ObjectInputStream objInStream = new ObjectInputStream(fileIn); tempStrng.equals(objInStream.readObject()); if(tempStrng!= null){ System.out.println(tempStrng); //no data } objInStream.close(); } catch (Exception ee) { ee.printStackTrace(); } } }
Patricia Shanahan - 21 Nov 2007 04:36 GMT >>> I am attempting to write data into a file and read it >>> back again. [quoted text clipped - 16 lines] > > I am not sure, at this point, if this is what was expected. ...
> tempStrng.equals(objInStream.readObject()); ...
This line tests whether the objects referenced by tempStrng and the objInStream.readObject() result are equal, but firmly ignores the result.
What did you intend this line to do?
Patricia
bH - 21 Nov 2007 05:07 GMT > >>> I am attempting to write data into a file and read it > >>> back again. [quoted text clipped - 29 lines] > > - Show quoted text - Patricia,
Honestly, I have no clue what to write there. I wanted to see what the strings may look like comparing it to the original "data"
At one point I even made up a structure that looked like the original data and expected that the stored data would replace what I had put there. it was another "duh"
In the beginning, the model I was using to look at this from http://www.java-tips.org/blog/java-se/serializing-arrays.htm
It was simple integers that were being used.
int[] array = new int [5]; array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50;
int[] tmp_array = new int [5];
// writing array to disk FileOutputStream f_out = new FileOutputStream("C:\ \myarray.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (array);
// reading array from disk FileInputStream f_in = new FileInputStream("C:\\myarray.data"); ObjectInputStream obj_in = new ObjectInputStream (f_in); tmp_array = (int[])obj_in.readObject();
for(int i=0;i<5;i++) System.out.println(tmp_array[i]);
.............. 10 20 30 40 50 .................
bH - 21 Nov 2007 06:10 GMT > > >>> I am attempting to write data into a file and read it > > >>> back again. [quoted text clipped - 76 lines] > > - Show quoted text - oops...
I missed the last letter in the address above when copying it...
http://www.java-tips.org/blog/java-se/serializing-arrays.html
bH
Roger Lindsjö - 21 Nov 2007 10:26 GMT >>> I am attempting to write data into a file and read it >>> back again. [quoted text clipped - 86 lines] > } > } I'm not sure what you are trying to do when reading the object back. Originally you stored a Object[][], and then you compare it to a String. The value of the comparison (true or false) is ignored and you happily continue with checking if your string is not null. Perhaps you wanted something like this:
import javax.swing.*; import java.io.*;
public class GetData extends JPanel {
Object[][] tempObj;
public void GetData () { System.out.println("inside GetData"); try { FileInputStream fileIn = new FileInputStream("C:\\myarray.data"); ObjectInputStream objInStream = new ObjectInputStream(fileIn); tempObj = (Object[][])(objInStream.readObject()); if(tempObj!= null){ for (Object[] oa: tempObj) { for (Object o: oa) { System.out.print(o); System.out.print(" "); } System.out.println(); } } objInStream.close(); } catch (Exception ee) { ee.printStackTrace(); } } }
Note, I have not compiled this.
//Roger Lindsjö
bH - 22 Nov 2007 15:53 GMT > >>> I am attempting to write data into a file and read it > >>> back again. [quoted text clipped - 129 lines] > > - Show quoted text - Hi Roger,
Thanks for your help. It looks great, compiles with no errors, but produced no lines of output.
I revised your work, to something that I understood. Your efforts were a clue what to write. It finally read the file after compiling (code below). I am now able to combine it to put it into the original table (not incuded here).
This was my challenge: Take a program that displayed data in a table, then break it apart, 1. Write that data to a file. 2. Get the data from the file. 3. Display it in the table that was originally used.
Simply "a game of reassembling all the puzzle parts that were tossed into the box in a specific order now displayed on the table top again for all to see".
Thanks to all for your patience and efforts,
bH
public class GetData extends JPanel { Object[][] tempObj = new Object[5][5]; public GetData () {
System.out.println(); System.out.println("inside GetData"); System.out.println();
try { FileInputStream fileIn = new FileInputStream("C:\\myarray.data"); ObjectInputStream objInStream = new ObjectInputStream(fileIn); for (int ia = 0;ia<5;ia++){ for (int ib = 0;ib<5;ib++) { tempObj[ia][ib] = objInStream.readObject(); System.out.print(tempObj[ia][ib]); System.out.print(" "); System.out.println(); } } objInStream.close(); } catch (Exception ee) { ee.printStackTrace(); } } }
Lew - 22 Nov 2007 16:32 GMT > public class GetData extends JPanel { It doesn't look like this class "is-a" JPanel. You use no JPanel functionality; on the contrary, all your visible output is via System.out.
Also, the intent of class names is usually clearer with a noun (DataGetter) than a verb, which latter is good for methods.
> Object[][] tempObj = new Object[5][5]; > public GetData () { Don't do major work inside a constructor.
> System.out.println(); > System.out.println("inside GetData"); [quoted text clipped - 20 lines] > } > } One point about safety. If the readObject() call blows up, you will never close your Streams. You should put close() calls in a finally{} block, after the Stream is instantiated, to ensure that they really do close.
public class DataGetter { public void getData() { FileInputStream fileIn = new FileInputStream("myarray.data"); if ( fileIn == null ) { return; } ObjectInputStream objIn; try { objIn = new ObjectInputStream(fileIn); } catch( IOException ex ) { objIn = null; logger.log( Level.SEVERE, "Open error on object input", ex ); } if ( objIn == null ) { try { fileIn.close(); } catch( IOException ex ) { logger.log( Level.SEVERE, "Close error on file", ex ); } return; }
try { for (int ia = 0; ia < 5; ia++) { for (int ib = 0; ib < 5; ib++) { temp [ia] [ib] = objIn.readObject(); System.out.print( temp [ia] [ib] ); System.out.print(" "); System.out.println(); } } } catch( IOException exc ) { logger.log( Level.SEVERE, "Processing error on object input", exc ); } finally { try { objIn.close(); } catch( IOException ex ) { logger.log( Level.SEVERE, "Close error on object input", ex ); } try { fileIn.close(); } catch( IOException ex ) { logger.log( Level.SEVERE, "Close error on file", ex ); } } } }
 Signature Lew
bH - 22 Nov 2007 17:57 GMT > > public class GetData extends JPanel { > [quoted text clipped - 114 lines] > > - Show quoted text - Hi Lew,
Thanks for your prompt reply,
In between failed runs, I sometimes went to the data file location and tossed the output file into the trash, restarted the computer, and began again. Never can tell what gets stuck in the mind of a Win xp after too many test runs/errors.
Now you gave me the code to correct that, but I haven't tested it yet.
Maybe I should exchange myself for the turkey bird that is baking in the oven!
You wonderful "helpers" in this forum, one straightens the bent knees, another improves the eyesight, another gets the person to look in the correct direction. How to recall it all? I do save the samples so that for future reference, so I have something to fall back on just in case I need a reference. But Win xp does a rotten job of looking up files/words. Or maybe I have forgotten the words to put into my 'Google Desktop" to query my files. UGH!
I am going back into the oven. Not done yet.
Thanks again,
bH
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|