5

I want to serialize some objects in my Java code. I don't want to put it in some random folder on the hard drive. I want it to be inside A FOLDER in my eclipse project folder. How do I make this folder and store my objects in it ?

Is this a good practice ? Will there be a problem if I try to make a self-contained JAR out of this project ?

david blaine
  • 5,683
  • 12
  • 46
  • 55

7 Answers7

6

Below source code shows how to create subfolder in current directory:

import java.io.File;

public class SourceCodeProgram {

    public static void main(String argv[]) throws Exception {
        File currentFolder = new File(".");
        File workingFolder = new File(currentFolder, "serialized");
        if (!workingFolder.exists()) {
            workingFolder.mkdir();
        }
        System.out.println(workingFolder.getAbsolutePath());
    }
}

When you run this source code and refresh Eclipse project you should see serialized directory in Eclipse project structure. Now you can use it and store all files in it.

In my app, when I want to store some data in hard drive, I always use user recommendation. I create application.properties file which contains key:

working.folder=/example/app-name

App reads this file at the start and creates this folder if it needs it. Second solution can be "app parameter". When I need only one or two parameters from users I read it from command line. For example user run my app using that command:

java -jar app.jar -dir /example/app-name

When user do not provide any folder I use default folder - current directory.

helpful links:

Community
  • 1
  • 1
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
3

It depends what information those serializable objects have.

Also if you want to have a folder inside your codebase (but deployed as a folder only), you can write code, to write or read files:

URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

Note directory should be in classpath.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
  • how do you do this in eclipse ? That is create folder inside your java project and then enable your code to write to and read from this folder ? – david blaine Mar 29 '13 at 11:01
  • 1
    I guess you are aware of the fact, any folder you create inside eclipse will actually be a folder in folder-system. – Himanshu Bhardwaj Mar 29 '13 at 11:02
  • So, say your project is ProjA, your source is in ProjA/src... Create a folder in ProjA/res from explorer and refresh in eclipse and you should see the folder there.(Here you can keep your serialized objects.) – Himanshu Bhardwaj Mar 29 '13 at 11:04
  • Himanshu, you could even incorporate the following answer about refreshing the project in Eclipse programmatically: http://stackoverflow.com/questions/5467902/how-to-refresh-eclipse-workspace-programatically – Stephan Branczyk Mar 31 '13 at 21:11
  • Thanks Stephan for the add-on. – Himanshu Bhardwaj Apr 01 '13 at 05:44
3

Steps:

  1. Right click your project's folder in the Package Explorer
  2. Locate the "New" menu item and hover it
  3. Locate "Folder" in the opened menu and click it
  4. Give your folder a name
  5. Click the "Finish" button at the bottom

This will create a folder that should be accessible from your working directory when running from within eclipse.

It is a bad idea to fiddle with files that are within the JAR file during runtime. Imagine a scenario when there are two or more JVMs running the same JAR, this will also mean they work with the same files and reading/writing to those files may cause collisions. You would generally want to separate those files from each other.

So unless those files are read-only, you should not include them in your JAR (otherwise it is fine)

Ben Barkay
  • 5,473
  • 2
  • 20
  • 29
  • need some code which can find out the full path name of that folder by only supplying it the name of the folder and or filename. please add. – david blaine Apr 08 '13 at 04:22
2

Aren't you better off writing to the user directory, e.g. in a subfolder like .myApp/?

You would do something like this to set up/initialize the directory:

File userDir = new File(System.getProperty("user.home"));
File storageDir = new File(userDir, ".myApp");
if (!storageDir.exists())
    storageDir.mkdir();
// store your file in storageDir

Have a look here to find out where userDir is usually located (though you don't necessarily need to care).

skirsch
  • 1,640
  • 12
  • 24
2

If you launch your program in Eclipse, then by default the current working directory of the process will be the project's root directory. Then you can initialize and use a directory named serialized in your project's root like this:

File serializedDir = new File("serialized");
if (!serializedDir.exists()) {
    serializedDir.mkdir();
}

Relative paths in your code will be relative the working directory, which is the project's root by default. You can change the default working directory in the launcher configuration.

It depends on your project whether this is a good solution or not. If you don't want/need to share the serialized objects with others then I see nothing wrong with this.

When using the Export function of Eclipse to create a jar from the project, keep in mind that the folder will be selected by default. You have to explicitly deselect it to exclude from the jar. (In any case, it's better to use Maven or Ant for generating jars instead of Eclipse, which you only have to configure once, so no need to worry of the directory getting included by accident.)

You probably also want to exclude the directory from version control.

janos
  • 120,954
  • 29
  • 226
  • 236
2

In order to do this you need two things: A) Access/Create the specific folder B) Actually serialize your objects and save them to disk.

For A) this is certainly answered by the other answers here which show how to: 1) Check if folder exists. 2) Create the folder if it does not exist. Additionally, projects launched in eclipse have as the working directory the eclipse project folder.

For B) you need to serialize your objects using the FileOutputStream . See http://www.tutorialspoint.com/java/java_serialization.htm . You can either serialize each object into a separate file, or create one class with an ArrayList (or some other data structure) that contains references to all the objects.

Below a sample Class doing just what you asked using Static Methods as I didn't want to have to instantiate an object. Also, you need to press F5 in your eclipse project to refresh the package explorer and view the new folder and files.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;


public class CreateDirAndSerialize {


    public static void main(String args[])
    {
        ArrayList<String> sampleString = new ArrayList<String> ();
        sampleString.add("Test1");
        sampleString.add("Test2");
        sampleString.add("Test2");
        //Get the directory
        File directory = getSerializedDirectory();
        writeObjects(directory, sampleString);
    }

    public static void writeObjects(File directory, Object object)
    {
        try
          {
             FileOutputStream fileOut =
             new FileOutputStream(directory+"//serializedData");
             ObjectOutputStream out =
                                new ObjectOutputStream(fileOut);
             out.writeObject(object);
             out.close();
              fileOut.close();
          }catch(IOException i)
          {
              i.printStackTrace();
          }
    }

    public static File getSerializedDirectory()
    {
        File serializedDir = new File("serialized");
        if (!serializedDir.exists()) {
            serializedDir.mkdir();
        }
        return serializedDir;   
    }

}

As the question referred to projects within eclipse, the above is for code within an eclipse project. If you want to interact with Eclipse itself, we are talking about eclipse plugin development which is another story entirely so you need to specify that.

Finally, you can also create a custom class holding any variables you want and instantiate a singleton object for containing all your other objects. There are however some limitations when serializing objects, e.g. : - Object references with static modifier are not serializable.

See this for some rules/tips for some serializable: http://www.xyzws.com/Javafaq/what-are-rules-of-serialization-in-java/208

Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

You can ignore Eclipse and create the directory (and files in it) programmatically, or manually.

Then, refresh your project explorer view in Eclipse, and voila, the directory and files are part of the view.

TheBlastOne
  • 4,291
  • 3
  • 38
  • 72