java - Loading from object file -
i want load information object file array of type "song"
public class song { string name; string singer; public void setname(string name) { this.name = name; } public void setsinger(string singer) { this.singer = singer; } public string getname() { return name; } public string getsinger() { return singer; } @override public string tostring() { return getname() + "\t" + getsinger() + "\n"; }
and how try read did not work
private void loadfromobj(file f) { objectinputstream ois = null; fileinputstream fis = null; try { song[] s = new song[100]; object obj; fis = new fileinputstream(f); ois = new objectinputstream(fis); while ((obj = ois.readobject()) != null) { (int = 0; < s.length; i++) { s[i] = (song) obj; } } ois.close(); fis.close(); // refreshtable(s); } catch (ioexception e) { e.printstacktrace(); } catch (classnotfoundexception e) { e.printstacktrace(); } }
the object file contain lines each line has song name , artist name separated space "\t"
this how write information object file
private void writetoobj(file f, song[] s) { song // array write file objectoutputstream oos = null; fileoutputstream fos = null; try { fos = new fileoutputstream(f); oos = new objectoutputstream(fos); (int = 0; < s.length; i++) { oos.writeobject(s[i].tostring()); oos.writeobject(null); } } catch (ioexception e) { e.printstacktrace(); } { try { oos.close(); fos.close(); } catch (ioexception e) { e.printstacktrace(); } } }
add "implements java.io.serializable" after "public class song".
for use objectinputstream class need implements java.io.serializable or java.io.externalizable , file must create objectoutputstream. parse text file object use
byte[] encoded = files.readallbytes(paths.get(path)); string file = new string(encoded, encoding);
and parse string object:
string[] vars = file.split("\t"); song song = new song(); song.setname(vars[0]); song.setartist(vars[1]);
Comments
Post a Comment