Can I set the file index to the start of the file? - java

I want to be able to read an object from a file after I streamed one out to it.
Now, It works fine when I am reading at the first time, but when I'm trying to read again (to another object), there is an exception I'm unable to handle.
Now, I'm guessing the file index got to the end of the file, therefore I cannot read again from it.
Am I wrong? If not, can I set the file index to the start of the file?
try{
Classba cb=new Classba();
FileOutputStream fos=new FileOutputStream(args[0]);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(cb);
FileInputStream fis=new FileInputStream(args[0]);
ObjectInputStream ois=new ObjectInputStream(fis);
Classba cb2;
cb2=(Classba)ois.readObject();
cb2.print();
Classba cb3; //*OK Till Here*//
cb3=(Classba)ois.readObject();
}

You can call the method reset() on your ObjectInputStream.

Related

in Java Programming, will the file (.txt, .ser etc) get overwritten when we rewrite on existing file?

if I Do like this:
FileOutputStream fos=new FileOutputStream("cse.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(Dictionary);
and Again if I write the same file using the another object of Same type Dictionary on the same file like
FileOutputStream fos=new FileOutputStream("cse.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(List);
Will that file get overwritten ?
If you write simply:
FileOutputStream fos=new FileOutputStream("cse.txt");
Then the old data will be lost and will get overridden by the new data.
However, if you write:
FileOutputStream fos=new FileOutputStream("cse.txt", true);
Then the old data will NOT be lost and the new data will be appended to the old one.
Here, the second argument true indicates that the bytes will be appended to the end of the file rather than overwriting the complete file.
See the documentation

Do I need to close a stream?

Do I need to close a FileOutputStream in the following example? And why?
FileOutputStream fos = new FileOutputStream("bytes.info");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
If there were no exceptions thrown, then the FileOutputStream would be closed by ooo.close().
An exception thrown in writeObject would prevent any of the streams from being closed. So the close call should be in a finally block.
There's the additional problem that the ObjectOutputStream could throw an exception in its constructor. It writes the stream header in the constructor which can cause an exception. In this case, the FileOutputStream needs to be closed, but calling oos.close() is not possible because there's no reference to the ObjectOutputStream. So you really need two separate calls to close, one for each stream, both in finally blocks.
Using try-with-resources takes care of all of this for you:
try(
FileOutputStream fos = new FileOutputStream("bytes.info");
ObjectOutputStream oos = new ObjectOutputStream(fos)
) {
oos.writeObject(data);
}
Yes, you need to close the stream. Leaving FileOutputStream unclosed creates a possibility that some data that has been successfully written to the stream does not get saved to the file. If a program opens multiple file streams, not closing them creates a possibility of failures due to running out of native resources (too many files opened simultaneously).
FileOutputStream manages native resources, which are released by the close method. The class has a finalizer, too, which releases resources as well. As part of releasing native resources, the stream finishes out the writing of buffered data, if there is any. However, since JVM does not guarantee that a finalizer is going to be called on every object, failure to call close creates a risk of leaving buffered data unwritten.
Of course you have to close the FileOutputStream file. If not sometimes the data you save into the file might not get saved and you will end up with an empty file after executing the program. And you might wanna use try with resources so you won't have to close it manually and can do the exception handling part both at once.
try (FileOutputStream fos = new FileOutputStream("bytes.info");
ObjectOutputStream oos = new ObjectOutputStream(fos));{
}catch(){}
Just in case if you are not using try with resources close the file streams in the finally block manually.
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream("bytes.info");
oos = new ObjectOutputStream(fos));
oos.writeObject(data);
}catch(){
}finally{
if(fos != null){
fos.close();
}
if(oos != null){
oos.close();
}
}
It is a must to check whether those file streams are null or not. Because if they are null then there will be another error. Still it's better to use try with resources.

How to get data blockwise from an outputstream in java?

I want to serialize a big object structure to store it to a sql database.
Object tree = getTree();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(tree);
String objectString = Base64.getEncoder().encodeToString(baos.toByteArray());
The problem is that the generated byte array by baos.toByteArray() is to large. It throws java.lang.OutOfMemoryError and it is to big to transfer it to the database at once. I'm looking for an option to get the generated byte array block by block from outputstream to work it off in a loop step by step.
Write the initial OutputStream to a temporary file (using FileOutputStream). also, make sure you close the ObjectOutputStream or it will be a malformed stream. Lastly, open your temp file as a FileInputStream and use that to stream into your database.
Forget about the base64-encoding and write the object directly to the Blob's output stream.

Problems with encrypt and decrypt

I'm trying to write code in Java that will encrypt file. I had used example from this site:
http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html
Everything works fine but I need code that will overwrite original file with encrypted one. I'd changed only this:
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("original.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("original.txt");
FileOutputStream fos2 = new FileOutputStream("original.txt");
Encryption works, but after decryption decrypted file is empty.
Can someone explain me what's the problem and how to solve it?
Thanks !
You shouldn't read and overwrite the same file simultaneously with FileInputStream and FileOutputStream. Often, you'll get lucky, but the behavior is going to vary based on the underlying system, and that's not good. Instead, write to a temporary file, then move the temporary file to the location of the original file.

How to convert from TimePrimitive to int?

I have some data values(of type TimePrimitive) which i need to write out to a file , but the method out.write() takes only the parameter as int so i need to find a way to convert my values to int
I think it is the wrong approach. If you want to write objects to a file, then you need to use an ObjectOutputStream to write to the file:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date());
oos.writeObject(myTimePrimitive);
oos.close();
The normal out.write(int) is used to write a simple byte to a stream, and it would be implicitely be used by the ObjectOutputStream class.
You can use an ObjectInputStream to read your object back.
Have you tried the getValue() method?
BTW, What platform are you using, Javascript itself does not have a TimePrimitive type, are you sure this isn't Java?

Categories