Java serialization, how identify and name one file for each object? - java

I want to save severals files using Stream to serialize objects, with one serializable object per file.
The reason why I want have one file per object is that I have a list of these objects, I am on Android and at the start of the applicaiton I want load all saved objects, this is the easy part.
But during the execution I want add new elements in this list, and delete elements. And I want update the folder with my files in the same time.
So I supposed I have to create one file per object. But may be there is another solution ?
The main problem is : how name each file ? To avoid overwrite a file, ...
I first thinked that I will have to name my files depending the name of a String given by the user, but I will have to check if the name file is valid,...
So may be the solution is to just name my files with an integer, and at the first load, I just continue the counter from the higher file ?
I suppose my problem is frequent, so what are your solutions to write during the execution a dynamic list of objects ?
Thanks you

Related

How to retrieve multiple files using FTPClient object in java?

I wanted to retrieve list of files (Say about 100 files) from a directory.
I used retrieveFileStream method in java FTPClient object to get the files individually.
While retrieving the files, I am getting socket exception several times in between and I have a retry logic to overcome that.
The problem is each socket exception is causing a delay of 10 seconds, which eventually impacts my code performance.
I want to make code changes such that all the files to be retrieved in a
single function. I tried listFiles method in FTPClient object to get all the files in the particular directory. But my directory is having huge number of files (Say about 10000), which again impacts my code performance.
Is there any method to get list of files by providing the required file names list as input parameter? Please help me on this.
I want to make code changes such that all the files to be retrieved in a
single function. I tried listFiles method in FTPClient object to get all the files in the particular directory. But my directory is having huge number of files (Say about 10000), which again impacts my code performance.
Is there any method to get list of files by providing the required file names list as input parameter?
There's no better solution than the one you already have.
Of course, except for spliting the job to multiple threads.

Create Folders recursively

I call a webservice and get the following data from it:
Name of the folder
Id of the folder
Id of the parent-folder (null if it is root)
I create ArrayLists (List<String>) for the names, the ids and the parent-ids. So the folder with the name on position "0" has the id and the parent-id on position "0" in these lists.
Now I need to recreate the same structure on my local file system. The user enters a root-directory ("C:\test" for example) that I need to use.
I guess that a recursive method would be the best thing to do, but I have no idea how to implement it.
Any ideas / hints?
I don't see how recursion helps you. I assume you get multiple sets of the data you present, implied by your explanation though you don't say so. You also don't say what order you get them in. I'd create a hashmap, using full path to each parent as a key, and an object representing the directory as a value. The directory object would contain pointers to all its child directories. I'd create that entire hashmap, then walk it top-down. If you don't get the data in the correct order to build it top-down, then you'll have to put them all in a list and search the list to create top-down order, or trust that you can build the list without the IDs and fill them in later

Monitor text file for changes in Java

I am trying to monitor a text file for a change in the one line of text it contains. The file is constantly being deleted and created with the same name and path but the content rarely changes.
I am trying to construct an if statement so that if the content of the file changes then the system will print to the console.
I have looked at this Stack Overflow question and tried using the java-diff-utils example found on this page, but I could not find a way to implement it to solve my problem.
Start by generating an MD5 of the original file, then using a background Thread, recalculate the MD5 and compare it with the original. When the hash changes, the file contents would have changed.
Check out MD5 Hashing Example
If you're using Java 7, you could use the Watcher Service to monitor changes to the file. This would replace the thread
"High-level" advice: you could...
Consume the file contents in a custom Object at app initialization, and store it in a static variable
Define a property for said object, returning a String which represents the contents of the file
Use a TimerTask to periodically instantiate a new instance of said custom Object representing the file, and...
... compare the two String properties, so that you can print out the
latter should they not be equal, and then overwrite the static variable's value with the newly instantiated object
Note that this is hardly the professional way to handle recurrent tasks or file comparison - it's just meant to give you a draft direction.

Java - overwriting specific parts of a file

I would like to update specific part of a text file using Java. I would like to be able to scan through the file and select specific lines to be updated, a bit like in a database, for instance given the file:
ID Value
1 100
2 500
4 20
I would like to insert 3 and update 4, e.g.
ID Value
1 100
2 500
3 80
4 1000
Is there a way to achieve this (seemingly) easy task? I know you can append to a file, but I am more interested in a random access
I know you can append to a file, but I am more interested in a random access
You're trying to insert and delete bytes in the middle of a file. You can't do that. File systems simply don't (in general) support that. You can overwrite specific bytes, but you can't insert or delete them.
You could update specific records with random access if your records were fixed-length (in bytes) but it looks like that's not the case.
You could either load the whole file into memory, or read from the original file, writing to a new file with either the old data or the new data as appropriate on a per line basis.
You can do so using Random Access files in java where you can place your current write and read position using available methods. you can explore more here
Load the file into memory, change your value, and then re-write the file
if there's a way to insert into a file without loading it, I haven't heard of it. You have to move the other data out of the way first.
unless you're dealing with huge files, frequently, performance isn't too much of a concern
As said by the previous answers, it's not possible to do that symply using streams. You could try to use properties, that are key, value pairs that can be saved and modified in a text file.
For example you can add to a file a new property with the command
setProperty(String key, String value)
This method adds a new property or, if already existing, modifies the value of the property with the choosen key.
Obviously, new properties are added at the end of the file but the lack of ordering is not a problem for performances because the access to the file is made with the getProperty method that calls the Hashtable method put.
See this tutorial for some examples:
http://docs.oracle.com/javase/tutorial/essential/environment/properties.html

File Processing

I'm writing a game in which user can create his own level and remove them also.
The only trouble is that I want files to be saved with names as level1, level2, level3 etc without asking user name of level.
While saving a game with level5 name it might be possible that any previous level with that name already exists. Is there any way to avoid such problems.
I mean before saving the name by which i should save should be known previously...
thanx...
You can make use of the methods provided by the java.io.File API, such as File#exists(). It returns a boolean. If it is true, then you can either append to the file, or create another one with a different filename (maybe a counter suffix?). You can append to any existing file using the another constructor of FileOutputStream taking a 2nd boolean argument which you set to true. You can also just stick to using this constructor without checking if the file exists, it will just create new one if file doesn't exist and it will just append if the file exists.
What is the expected behavior in case level5 already exists and the user tries to save level 5? Should the old level5 file be overridden? If not, what else should happen? Should the new file me saved under a different name? And how is your game later on finding this level? If there are multiple level5 files for the 5th level, how shall your game know which one to pick?
Of course you could always create a UUID (that is more or less guaranteed to be unique in practice), create a directory named after that UUID and store the files into the directory as level1 to level5. Next time the user opens the level editor you create a new UUID, thus avoiding any naming conflicts.
Or you can turn it around. You crate a directory name level1, level2, etc. and within each directory you store the files using file names that contain a UUID. That way the game can always easily present a list of all level 5 levels by going into the level5 directory and looking at all files found there.
The question is rather: How will you present those levels to the user when it comes to picking one? As you don't have names, you hardly want to show UUIDs to the user. So I wonder if it is not better to let the user name levels or set of levels (directories).
It seems that your problem is not how but what. Reconsider your goal (desired functional requirements).
If user cannot provide a unique (and meaningful) name for created level, how will he refer to that level (for example in case he wants to edit it)?
I think you should keep additional data for every level like: name (unique), author, maybe date of creation, date of last modification, etc. When user saves (creates or edits) a level he should be warned in case level with provided name exists and should choose between cancel/overwrite/try_another_name. Probably user should be prohibited from overwriting a level when he is not the author.
The best (natural) way to store and process above data is to use a database.

Categories

Resources