I want a "simple" method so i can store shared objects in the disk, and then i can retrieve these so's from the disk even the red5 server restarts.
PS: i wasted many hours on finding good doc that explains the procedure but i found none.
Just notice that every field in your object should be serializable, then you can refer to this code sample:
import java.io.Serializable;
#SuppressWarnings("serial")
public class Person implements Serializable{
private String name;
private int age;
public Person(){
}
public Person(String str, int n){
System.out.println("Inside Person's Constructor");
name = str;
age = n;
}
String getName(){
return name;
}
int getAge(){
return age;
}}
**
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeToFlatFile {
public static void main(String[] args) {
SerializeToFlatFile ser = new SerializeToFlatFile();
ser.savePerson();
ser.restorePerson();
}
public void savePerson(){
Person myPerson = new Person("Jay",24);
try {
FileOutputStream fos = new FileOutputStream("E:\\workspace\\2010_03\\src\\myPerson.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Person--Jay,24---Written");
System.out.println("Name is: "+myPerson.getName());
System.out.println("Age is: "+myPerson.getAge());
oos.writeObject(myPerson);
oos.flush();
oos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void restorePerson() {
try {
FileInputStream fis = new FileInputStream("E:\\workspace\\2010_03\\src\\myPerson.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person myPerson = (Person)ois.readObject();
System.out.println("\n--------------------\n");
System.out.println("Person--Jay,24---Restored");
System.out.println("Name is: "+myPerson.getName());
System.out.println("Age is: "+myPerson.getAge());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}}
Related
I need to save an arraylist in a txt when I close a window and load it when I return to open the program so that it shows what is saved in a JTable.
This is my arraylist
ArrayList<Usuarios> Encuestados = new ArrayList<>();
And I'm saving in this way but I would not know how to load the saved txt to the arraylist
public void guardarTxt() throws FileNotFoundException, IOException, ClassNotFoundException{
FileOutputStream fout=new FileOutputStream("Datos/Encuestados.txt");
try (ObjectOutputStream out = new ObjectOutputStream(fout)) {
out.writeObject(Encuestados);
}
}
You just need to serialize and deserialize the objects in the array. You can search for serialize and deserialize objects in java. I have implemented a code below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class Usuarios implements Serializable { // will need to implement Serializable class
private static final long serialversionUID = 129348938L; // this is needed
String name;
int age;
// Default constructor
public Usuarios(String name, int age) {
this.name = name;
}
}
public class Main { // Example class for Serialization and deserialization
// method for printing the object
public static void printdata(Usuarios object1) {
System.out.println("name = " + object1.name);
System.out.println("age = " + object1.age);
}
public static void serialize(ArrayList<Usuarios> list, String filename){
// Serialization
try {
// Saving of object in a file
FileOutputStream file = new FileOutputStream
(filename);
ObjectOutputStream out = new ObjectOutputStream
(file);
// Method for serialization of object
out.writeObject(list);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
}
public static ArrayList<Usuarios> deserialize(String filename){
// Deserialization
try {
// Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
// Method for deserialization of object
ArrayList<Usuarios> list = (ArrayList<Usuarios>)in.readObject();
System.out.println("Object has been deserialized");
in.close();
file.close();
return list;
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
}
public static void main(String[] args) {
Usuarios object1 = new Usuarios ("ab", 20);
Usuarios object2 = new Usuarios ("cd", 21);
String filename = "s.txt";
ArrayList<Usuarios> EncuestadosBeforeSerialization = new ArrayList<>();
EncuestadosBeforeSerialization.add(object1);
EncuestadosBeforeSerialization.add(object2);
System.out.println("Data before Deserialization.");
for (Usuarios object: EncuestadosBeforeSerialization) {
printdata(object);
};
serialize(EncuestadosBeforeSerialization, filename);
System.out.println("\n\nData will be Deserialize.");
ArrayList<Usuarios> EncuestadosAfterSerialization = deserialize(filename);
System.out.println("Data after Deserialization.");
for (Usuarios object: EncuestadosAfterSerialization) {
printdata(object);
};
}
}
Result:
Data before Deserialization.
name = ab
age = 0
name = cd
age = 0
Object has been serialized
Data will be Deserialize.
Object has been deserialized
Data after Deserialization.
name = ab
age = 0
name = cd
age = 0
I want to read and write an object to a file. This is my attempt:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class SaveOpen implements Serializable
{
private static String fileName;
private ArrayList<Person> list = new ArrayList<Person>();
public SaveOpen() {
fileName = "file.txt";
}
//Reader
public static Object deserialize() throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
ois.close();
return obj;
}
//Writer
public static void serialize(Object obj)
throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ArrayList<Person> getListPersons() {
return list;
}
}
However, I do not know if this is the correct way nor how to implement this in a class. The object is Person and I want to save and read that object from a file. Is it supposed to be done to a .txt file? Anyone who can clearify things? Thanks!
if you want the file to be human readable i would suggest to save it as xml.
Example :
Object Class
import java.io.Serializable;
public class Person implements Serializable
{
private String username;
private int id;
public String UserName() { return username; }
public void setUserName(String str) { username = str;}
public int ID() { return id; }
public void setID(int ID) { id = ID; }
}
-Serializer/Deserializer
import Settings.Person;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class XmlSerializer
{
//File path to serialize to and deserialize from
private static final String SERIALIZED_FILE_NAME = "yourSavePath.xml";
//Insert person object and save as xml file to chosen filepath
public static void Serialize(Person person)
{
try
{
FileOutputStream os = new FileOutputStream(SERIALIZED_FILE_NAME);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(person);
encoder.close();
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
//Deserialize xml file into person object
public static Person Deserialize()
{
try
{
FileInputStream os = new FileInputStream(SERIALIZED_FILE_NAME);
XMLDecoder decoder = new XMLDecoder(os);
Person p = (Person)decoder.readObject();
decoder.close();
return p;
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
return null;
}
}
You're doing it right already. You can safe Objects in a txt file altough it makes not much sense, I'd rather go with a binary file.
To store multiple Objects in a single File, simply pack them in a Collection and then serialize the Collection object.
When reading an Object from a File, check its Class via instanceof and cast it to whatever it is.
I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]
Serializing data through
try {
FileOutputStream fileOut = new FileOutputStream(
"C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(r);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reg.ser");
pr.println("Registered Successfully ");
} catch (IOException i) {
i.printStackTrace();
}
and while Deserializing not getting entire file objects only getting single object i.e starting object only .
FileInputStream fileIn = new FileInputStream("C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser");
ObjectInputStream in = null;
while (fileIn.available() != 0) {
in = new ObjectInputStream(fileIn);
while (in != null && in.available() != 0) {
r = (Registration) in.readObject();
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
if (r.u.equals(ur) && r.p.equals(ps)) {
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
pr.println("Display");
}
}
}
I have created the working sample for you .
My POJO serializable class will be ,
import java.io.Serializable;
public class Pojo implements Serializable{
String name;
String age;
String qualification;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
My main class will be,
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Serialization {
/**
* #param args
*/
public static final String FILENAME = "F:\\test\\cool_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
//ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(FILENAME);
//oos = new ObjectOutputStream(fos);
/* for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}*/
for(int i=0;i<10;i++){
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pojo pojo = new Pojo();
pojo.setName("HumanBeing - "+i);
pojo.setAge("25 - "+i);
pojo.setQualification("B.E - "+i);
oos.writeObject(pojo);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
//ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILENAME);
//ois = new ObjectInputStream(fis);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
for (int i=0; i<results.size()-1; i++) {
System.out.println(((Pojo)results.get(i)).getName()+ " "+((Pojo)results.get(i)).getAge()+ " "+((Pojo)results.get(i)).getQualification());
}
}
}
Hope it helps.
I have a homework to retrieve a myqsl query and save it to a ArrayList , and then to link it to another class and then serialize it and send it through http,
In a scheme it would be
class Server{static class a {try{try{ try{arraylist1} }}}}
class b {var1,var2,link_to(arraylist1)}
then serialize class b and send it
i managed to take the sql query and save the objects in the ArrayList (objects created from class "Personat") through
if (rs != null) {
List<Personat> perList = new ArrayList<Personat>();
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("var1"));
per.setName(rs.getString("var2"));
per.setAmount(rs.getInt("var3"));
perList.add(per);
}
}
Where rs=ResultSet object
but i cant access the ArrayList from class b so i can serialize it. I have tried to make it static (nothing ,it cant be linked).I have tried to make a getter (yet nothing eclipse wont let me as i automatically generate them).
So i don't know what i should do ! Can someone help me ? Or does anyone have any idea?
i have tried to search google for this but as you can see is a little too specific so no results until now ....
here is my Server.java
package server2;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private static List<Personat> perList = new ArrayList<Personat>();
//need to access this in the SendRes class
public List<Personat> getPerList() {
return perList;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static public class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
ResultSet rs = s.executeQuery("SELECT * "
+ "from personat ORDER BY EmpId");
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//here i need to send an SendRes object with the ArrayList inside it
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SendResponse implements Serializable {
String gabim;
String gabimNr;
//link the arraylist from class server here
}
class Personat {
int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
String Name;
int Amount;
}
Objects of type B can only access the public members of type A. To get access to your list you need to make it a public member of A. The typical way to do this is to use a private field and a public getter.
class A
{
private List<Personat> personList;
public List<Personat> getPersonList() { return personList; }
public void handle(HttpExchange t) throws IOException
{
// ...
personList = ...;
// ...
}
}
Note that by giving public access to your list you are also allowing clients to modify the contents of the list. You may prefer to give them a copy of the list if this is not desirable.
On a slightly unrelated note, if you three nested try blocks in a single method then that method is probably too complex and should be refactored into smaller methods.