Retrieving a String array from a file using ObjectInputStream in Java? - java

My program is basically a daily planner.
The schedule is saved in files by month and year by ObjectOutputStream. check
The schedule is arranged in an array by day. check
The schedule is retrieved by ObjectInputStream. This is where I have problems.
public class Calendar {
public String date;
public String[] schedule = new String[31];
Calendar(){
}
public String retrieve(int month, int day, int year) {
date = Integer.toString(month) + "-"+ Integer.toString(year ) + ".txt";
try {
ObjectInputStream input = new ObjectInputStream(new
FileInputStream(date));
input.readObject();
schedule = input;
//This is where I have the error obviously schedule is a string array and
//input is an ObjectInputStream so this wont work
input.close();
return schedule[day-1];
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "File not found";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "IOException";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "ClassNotFound";
}
}
public void save(int month, int day, int year, JTextArea entry) {
date = Integer.toString(month) + "-"+ Integer.toString(year ) + ".txt";
schedule[day-1]= entry.getText();
try {
ObjectOutputStream output = new ObjectOutputStream(new
FileOutputStream(date ));
output.writeObject(schedule);
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The schedule will be displayed in a text area using something like
entry.setText(calendar.retrieve(month,day,year));

ObjectInputStream input = new ObjectInputStream(new FileInputStream(date));
OK.
input.readObject();
Pointless. This method returns the object that was read. You need to store it into a variable.
schedule = input;
Also pointless. input is an ObjectInputStream that you're about to close. Saving it in another variable is futile.
//This is where I have the error obviously schedule is a string array and
//input is an ObjectInputStream so this wont work
input.close();
It should be
schedule = (String[])input.readObject();

Related

last object serialized gets overwritten

I am writing a program for keeping track of library books. There is an object book that includes a title, sku number, price and quantity. All the books are stored in an Array List. I'm trying to serialize the books and add new books but every time a book is added the last is overwritten.
here is the code below to load objects from save
public static void readSave() {
File stockFile = new File("inventory.txt");
try {
if(!stockFile.createNewFile() && stockFile.length() != 0) {
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(stockFile));
int size = objIn.readInt();
for(int i = 0; i < size; i++) {
Book t = (Book) objIn.readObject();
bookList.add(t);
}
objIn.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here is my save method and it is set to save every time the program executes.
public static void save() {
File inventoryFile = new File("inventory.txt");
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(new FileOutputStream(inventoryFile));
objOut.writeInt(bookList.size());
Iterator<Book> i = bookList.iterator();
while(i.hasNext()){
objOut.writeObject(i.next());
}
objOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
below is my main method which calls these functions
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readSave();
CampusBookWindow window = new CampusBookWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
save();
}
});
}
My problem was when I hit the add book button I would not create a new book object for that item, but instead I was reassigning that last book object so the object last book object was erased from the bookList array list

Why am I getting InvocationTargetException at ClassLoaders.callStaticFunction Java Eclipse? [duplicate]

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

Trouble with readObject only returning a single array value

I'm taking a course in Java, and the assignment is to write a calendar program that can write and retrieve events from a file.
My problem is that I'm only getting the first value of my written array. returned from the "input.readObject"
Here is my getFile method calling looking to read the file.
static String[] Entry = new String [35];
public static void getFile(Object month, String year) throws IOException
{
ObjectInputStream input = new ObjectInputStream(new FileInputStream(month+year+".txt"));
try
{
String[] LoadedEntry = (String[])(input.readObject());
Entry = (String[]) LoadedEntry;
}
catch (IOException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File not found, creating new file...");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
input.close();
}
}
And the method that calls it, and writes the desired code after the getFile method executes.
public static void saveEvent(String month, int day, String year, String calendarEvent)
{
String[] EntryF = new String[35];
String[] Sample = {"1", "2", "3", "4", "5"};
try
{
getFile(month, year);
System.out.println("Past getFile");
EntryF = Entry;
//EntryF = Sample;
EntryF[day] = calendarEvent;
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(month + year+".txt", true));
output.writeObject(EntryF);
output.reset();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Been racking my brain for all day, and cannot get this thing to work... Does anyone see where I went wrong?
I can verify that the object is being saved and passed down into the saveEvent method because the written textfile is changing, but it's just not reading in the full contents of the file correctly..
Thanks,
Andy
You will need a loop to read rest of the stream. So far you are reading just the first part of the stream, so the following will have to be in a loop:
String[] loadedEntry = (String[])(input.readObject());
And you will also need to determine a signal to use to end the loop.
For e.g. using input.read() will result in -1 when the end of stream is reached.
You can read the entire file with something like the following:
try {
while (Terminating_Condition) {
String[] loadedEntry = (String[]) (input.readObject());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope that helps.

Trouble Receiving image over socket

im tryin to send an image over socket , the sender part -(android)- looks short and ok, but the receiver part - which is written by java - is supposed to rename the image and save it in the C:/... . but i get nothing there and i cant find any problem with it ..
here is my server code:
public void start() throws InterruptedException {
keepGoing = true;
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a hread of it
jobdone=false;
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) +
" Exception on new ServerSocket: " + e +
"\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("192.168.1.2", 1500);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
// create a server object and start it
public static void shutdown() {
jobdone = true;
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
String Type;
Socket socket;
InputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object I/O Streams");
// create output first
int bytesRead = 0;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
InputStream is = null;
try {
is = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("C:/IMG-20130112-WA0011.jpeg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // destination path and name of file
//FileOutputStream fos = new FileOutputStream("C:/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
try {
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
current = bytesRead;
do {
try {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
try {
bos.write(mybytearray2, 0 , current);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long end = System.currentTimeMillis();
//System.out.println(end-start);
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
am i doing any thing wrong guys ? thanks for reading in advance
The file path should be C:// instead of C:/

Serialization of a class which doesnt implement Serializable

I have 2 classes serial1 and serial 2. serial1 implements Serializable whereas serial2 does not.As per theory i should get an Exception for the following code, but it is working fine. why is it so ?
import java.io.*;
public class SerialTest {
public static void main(String args[]){
FileOutputStream fos=null;
ObjectOutputStream oos =null;
serial1 se = new serial1();
serial1 sd = null;
se.mets();
try {
fos= new FileOutputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos =new ObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(se);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis=null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sd = (serial1) ois.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sd.mets();
}
}
import java.io.Serializable;
public class serial1 implements Serializable{
/* public static void main(String []args){
serial1 ss = new serial1();
ss.mets();
}*/
public void mets(){
serial2 s2 = new serial2();
System.out.println( "serial 1 + mets");
s2.met1();
}
}
public class serial2 {
public void met1(){
System.out.println("serial2 + met1");
}
}
---------------------------*
The output is
serial 1 + mets
serial2 + met1
serial 1 + mets
serial2 + met1
You don't actually serialize serial2. Your mets method creates a local variable but as soon as the method returns it goes out of scope and becomes eligible for garbage collection.
If you had an instance variable of type serial2 inside serial1 then you would see an exception when you try to serialize (assuming it's a non-null value), but a local variable will not be a problem.
I don't see you ever serializing serial2

Categories