I am using Weka SMO to classify my training data and I want to save and load easily to/from file my SMO model. I have created a save method in order to store Classifier to file. My code is the following:
private static Classifier loadModel(Classifier c, String name, File path) throws Exception {
FileInputStream fis = new FileInputStream("/weka_models/" + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
return c;
}
private static void saveModel(Classifier c, String name, File path) throws Exception {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("/weka_models/" + name + ".model"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
oos.writeObject(c);
oos.flush();
oos.close();
}
My problem is, how to convert ObjectInputStream to Classifier object.
Ok it was an easy one, I ve just had to use readObject.
private static Classifier loadModel(File path, String name) throws Exception {
Classifier classifier;
FileInputStream fis = new FileInputStream(path + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (Classifier) ois.readObject();
ois.close();
return classifier;
}
Related
/**
* A method that writes variables in a file for shows in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void writeShowData(String fileName) throws FileNotFoundException{
String showPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{
FileOutputStream fos = new FileOutputStream(showPath+fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(show);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void readShowData(String fileName) throws FileNotFoundException {
try
{ FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List <Show>shows =(List<Show>)ois.readObject();
ois.close();
System.out.println(shows.toString());// for testing
}
catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
the line : List <Show> shows= (List<Show>)ois.readObject(); gives a
ClassCastexception :class Show cannot be cast to class java.util.List
(etc etc....
I tried many things but can't get it working well.
I made the class show and related classes
Serializable and then write it to shows.ser but when it reads it goes wrong.
Who can help me out on this?
I solved your problem as below. Firstly, you need to change your writing method. If a data file does not exist, you need to create a regular (without append) FileOuputStream for stream header otherwise you will get java.io.StreamCorruptedException (ref). FileOutputStream should be created differently for the next additions.
public static void writeShowData(String fileName) {
String showPath = "E:\\path\\";
try {
File file = new File(showPath + fileName);
ObjectOutputStream oos;
if(file.exists()) {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), true); // with reset fos
oos = new ObjectOutputStream(fos) {
protected void writeStreamHeader() throws IOException {
reset();
}
};
} else {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); // regular fos
oos = new ObjectOutputStream(fos);
}
oos.writeObject(show);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Secondly, you need to modify your reading method. If your FileInputStream has data, you need to iterate to add your list.
public static void readShowData(String fileName) {
try {
FileInputStream fis = new FileInputStream("E:\\path\\" + fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List<Show> shows = new ArrayList<>();
while (fis.available() > 0) {
Show s = (Show) ois.readObject();
System.out.println(s.number);
shows.add(s);
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
here is my latest version that is working, the new code does leave out a few lines like if(file.exists){file.delete()}.etc... because the used streams doing that automaticly.
i totally overwrite the file(s) with an update method instead of writing one object at a time.
The earlier answers and some testing by myself made me understand how to get it done right for the purposes in my code.
/**
* A method that writes/saves variables of an Arraylist in a file for seatReservations in the program.
*
* #author Willem
* #version (1.6 2022.01.20)
*/
public void overWriteShowData(String fileName1) throws FileNotFoundException {
String seatReservationPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{ File file = new File(seatReservationPath + fileName1);
ObjectOutputStream oos;
FileOutputStream fos = new FileOutputStream(file.getCanonicalPath(),false); // regular fos
oos = new ObjectOutputStream(fos);
oos.writeObject(shows);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.6 2022.01.20)
*/
public void readShowData(String fileName1) throws IOException, EOFException,ClassNotFoundException{
FileInputStream fis = new FileInputStream(fileName1);
ObjectInputStream ois = new ObjectInputStream(fis);
shows = (List<Show>) ois.readObject();
ois.close();
}
private void updateAllData(String fileName) {
try {
if(fileName.equals("theatres.ser"))
{overWriteTheatreData(fileName);}
if(fileName.equals("seatPlans.ser"))
{overWriteSeatPlanData(fileName);}
if(fileName.equals("shows.ser"))
{overWriteShowData(fileName);}
if(fileName.equals("customers.ser"))
{overWriteCustomerData(fileName);}
if(fileName.equals("seatReservations.ser"))
{overWriteSeatReservationData(fileName);}
} catch (FileNotFoundException fnfe) {
//fnfe.printStackTrace();
CinemaReservationSystemGUI.cannotFindFileMessage(fileName);
}
}
Considering I have an object from a custom class and I write it to a .dat file using FileOutputStream and ObjectOutputStream . How will I modify a object present in the file? I can only read or write objects into a file..
I know that we can create a temporary file and then renaming the file accordingly, but isnt there any other way?
I do get outputs as expected , but isnt there any other method?
Yes you can do it by using FileOutputStream & ObjectOutputStream class
class MyBean {
public String firstvalue;
public String secondvalue;
public MyBean (String firstvalue,String secondvalue){
this.firstvalue=firstvalue;
this.secondvalue=secondvalue;
}
}
public class FileSerialization {
public static void main(String[] args) {
try {
MyBean mb = new MyBean("first value", "second value");
// write object to file
FileOutputStream fos = new FileOutputStream("mybean.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(mb);
oos.close();
// read object from file
FileInputStream fis = new FileInputStream("mybean.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
MyBean result = (MyBean) ois.readObject();
ois.close();
System.out.println("One:" + result.firstvalue + ", Two:" + result.secondvalue);
result.firstvalue="Changed;";
// write object to file
fos = new FileOutputStream("mybean.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(result);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public class MakeNewFile{
static HashMap<String, User> hm = new HashMap<String, User>();
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello!!");
try{
File inputFile = new File("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");
System.out.println("Done");
boolean resut = inputFile.createNewFile();
System.out.println(resut);
System.out.println("File found");
//fileInputStream = new FileInputStream(inputFile);
FileInputStream fileInputStream = new FileInputStream(inputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//out.println("hiii2");
hm= (HashMap)objectInputStream.readObject();
System.out.println("hiii" +hm);
if(hm.containsKey("username"))
{ String error_msg = "Username already exist as " + "usertype";}
else{
User user = new User("firstname", "lastname", "email", "username","password","usertype");
hm.put("username", user);
FileOutputStream fileOutputStream = new FileOutputStream("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(hm);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
}
}
catch(Exception ex){
}
}
}
The file is not creating while running the code. Code is not executing of try block after FileInputStream. Where is the problem?
I tried one solution. File has been created but objectInputStream is not available.
After running the code locally, the exception thrown is an EOF exception - java.io.EOFException. A solution would be to do a check to see if the fileInputStream is available:
if (fileInputStream.available() > 0) {
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//out.println("hiii2");
hm = (HashMap) objectInputStream.readObject();
}
I have an issue with the input I am getting from reading a file.
The file is made in another activity and is very simple:
ArrayList stuff = new ArrayList();
stuff.add("1,2,3");
try{
String saveFile = "saveGamesTest1.csv";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream save = new ObjectOutputStream(saveGames);
save.writeObject(stuff);
save.close(); }
In the other activity it's being read via
try {
FileInputStream fileIn=openFileInput("saveGamesTest1.csv");
InputStreamReader InputRead = new InputStreamReader(fileIn);
Scanner s = new Scanner(InputRead).useDelimiter(",");
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
}
I was expecting (and hoping) to get a result back like
1
2
3
However, the result I'm getting is this:
/storage/emulated/0/Android/data/ys.test/files/saveGamesTest1.csv����sr��java.util.ArrayListx����a���I��sizexp������w������t��1
2
3x
What am I doing wrong?
.
EDIT
I tried Serializable as suggested below, like follow:
public class Save implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
}
public void save(){
Save e = new Save();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
String saveFile = "save.ser";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream out = new ObjectOutputStream(saveGames);
out.writeObject(e);
out.close();
saveGames.close();
System.out.printf("Serialized data is saved in save.csv");
}
catch(IOException i) {
i.printStackTrace();
out.println("Save exception gepakt");
}
}
However, out.writeObject(e); gives an error saying that this isn't Serializable
You are not storing object as csv but as serialize java object you have to read as an object not as a csv file
take a look here https://www.tutorialspoint.com/java/java_serialization.htm
at Serializing an Object part
You have to use
FileInputStream in = null;
ObjectInputStream ois = null;
ArrayList stuff2 = null;
try {
in = openFileInput("saveGamesTest1.csv");
ois = new ObjectInputStream(in);
stuff2 = (ArrayList) ois.readObject();
} catch(IOException e) {...}
catch(ClassNotFoundException c) {...}
finally {
if (ois != null) {
ois.close();
}
if (in != null) {
in.close();
}
}
If you want a csv file you have to build it for instance by iterate over your array and write one by one the value in your file and adding the separator or follow this
How to serialize object to CSV file?
EDIT :
An elegant way in Java 7 to serialize an object (here a list like in your example) and deserialize :
public class Main {
public static void main(String[] args) {
List<Integer> lists = new ArrayList<>();
List<Integer> readList = null;
String filename = "save.dat";
lists.add(1);
lists.add(2);
lists.add(3);
//serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(lists);
} catch (IOException e) {
e.printStackTrace();
}
//don't need to close because ObjectOutputStream implement AutoCloseable interface
//deserialize
try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(filename))) {
readList = (List<Integer>) oos.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
//don't need to close because ObjectInputStream implement AutoCloseable interface
//test
if(!lists.equals(readList)) {
System.err.println("error list saved is not the same as the one read");
}
}
}
I want to save values as an ArrayList of double in a file. Whenever there is new value, it should be added in an ArrayList without erasing the previous ones. I'm try to use the function,DataStream. Is it possible? If its possible, please let me know how to implement that.
Please refer below code .
private static String LFILE = "serial";
public static void updateFile(Double num) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
List<Double> list = getDoubles();
list.add(num);
fos = new FileOutputStream(LFILE);
oos = new ObjectOutputStream(fos);
oos.writeObject(list);
}catch(Exception e){
e.printStackTrace();
try {
oos.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static List<Double> getDoubles() {
FileInputStream fis = null;
ObjectInputStream ois = null;
List<Double> newList = new ArrayList<Double>();
try {
fis = new FileInputStream(LFILE);
ois = new ObjectInputStream(fis);
newList = (ArrayList<Double>) ois.readObject();
} catch (Exception ex) {
try {
fis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return newList;
}
The class you want to use are ObjectOutputStream and ObjectInputStream
e.g.
http://www.javadb.com/writing-objects-to-file-with-objectoutputstream
http://www.javadb.com/reading-objects-from-file-using-objectinputstream
XStream is a library for Java which supports save/send objects in a xml-format. It is simple to use. XML is human readable making it easy to check its corrent or modify.