When I serialize my class and save it as a custom file extension, some of the variables and imports are visible when you open the file in a text editor. Is there a way to avoid this or is there an alternate method to save class instances as a file? My file saving code:

//Make file
FileOutputStream fileOut = new FileOutputStream("fileName.ext");
ObjectOutputStream out;
out = new ObjectOutputStream(fileOut);

The instanceToSave is a class instance in which the class implements java.io.Serializable.

Note: I do not mean transient variables.

  • 2
    So what exactly are you trying to find out here? If you want to know serialization's default behavior in Java, Snowman's answer is spot-on. If you want to know how to obfuscate serialized data, you probably need to phrase your question differently, or head to Stack Overflow. – h.j.k. Jun 11 '15 at 3:07

First of all, I highly recommend you read up a little on Java serialization. This article is a bit dated but covers the essentials.

Specifically, this bit is important:

2. Serialization is not secure

It often comes as an unpleasant surprise to Java developers that the Serialization binary format is fully documented and entirely reversible. In fact, just dumping the contents of the binary serialized stream to the console is sufficient to figure out what the class looks like and contains.

This means that the default serialization cannot be relied upon to obfuscate or secure the contents of objects.

However there is a way that may be able to achieve what you need. You can write custom serialization methods on the class being serialized where you can transform data however you want. Keep in mind that at best you can hope to obfuscate or slow down someone from reading the data.

public class MyClass implements Serializable {
  private String secret;
  private void writeObject(ObjectOutputStream out) throws IOException {

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    ename = decrypt(in.readUTF());

  private String encrypt(String plaintext) {
    return ...;

  private String decrypt(String ciphertext) {
    return ...;
  • I think the decrypt method should have an argument of String encryptedtext instead of String plaintext. – setzamora Jun 11 '15 at 5:28
  • 1
    @Joset you are correct and I fixed it. You can always suggest an edit. If accepted you get a little bit of rep, too. – user22815 Jun 11 '15 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.