How should you handle a FileSystemAlreadyExistsException when calling FileSystems.newFileSystem?
One way would be to use the already created FileSystem (getFileSystem), but then you could run into problems when the original creator closes it while you are still using it.
In case there is no generic answer to this question, then what about ZipFileSystems? Let's say I want to create one for a zip file and I do not know and cannot control whether a FileSystem already exists for this specific zip file.
Is there a reliable way to handle a FileSystemAlreadyExistsException?
Sorry for being late here, but I just ran into this myself. There are several versions of the FileSystems.newFileSystem() call, some versions throw FileSystemAlreadyExistsException, some do not. I found that using the version that accepts a Path object did not throw the exception and allowed me to work around the issue I was having.
Try putting a try/catch block around the code that is causing the exception.
Related
First of all this might be a dumb question and I searched for some days but didn't find an answer. So if there is an existing answer concerning my question, I would be grateful for a link.
I don't know if anyone of you ever coded Spigot, Paper or Bukkit, but there was a class called YamlConfiguration which had the following methods:
public FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
cfg.set(path.path2, "hello");
cfg.getInt/String/...(path.path2); (which obviously returns "hello")
cfg.save(file);
The produced file then looks like this:
path:
path2: "hello"
So you could basically save any value in those files and reuse them even if your program has been restarted.
I know have moved forward from Spigot/Paper to native Java and I'm missing something like that Yaml-thing. The only thing I found was a kind of a config file, where every time the whole file is overwritten, when I try to add values.
Can you show me a proper way of saving values to a file? (would be nice without libraries)
I'm missing sth like that Yaml-thing
SnakeYAML should have you covered. Without knowing anything about your use-case, it makes no sense to discuss its usage here since its documentation already does cover the general topics.
The only thing I found was a kind of a config file, where everytime the whole file is overwritten, when I try to add values.
Saving as YAML will always overwrite the complete file as well. Serialization does not really work with append-only. (Serialization is the term to search for when you want functionality like this, by the way.)
If you mean that previous values were deleted, that probably was because you didn't load the file's content before or some other coding error, but since you don't show your code, we can only speculate.
Can you show me a proper way of saving values to a file?
People will have quite different opinions on what would be a proper way and therefore it is not a good question to ask here. It also heavily depends on your use-case.
would be nice without libraries
So you're basically saying „previously I used a library which had a nice feature but I want to have that feature without using a library“. This stance won't get you far in today's increasingly modular software world.
For example, JAXB which offers (de)serialization from/to XML was previously part of Java SE, but has been removed as of Java SE 11 and is a separate library now.
I have a procedure that has one in parameter and two out parameters.
I would like to make my code more generic in such a way that,
if in future any procedure will come then I will just create one properties file of it and update.
Code will automatically work accordingly and setString and RegisterOut parameters.
Short Answer: Stop reinventing the wheel.
Use an existing tool to solve this problem.
Accept This:
You will never encounter a problem that has never before been encountered.
You will never come up with a totally new and novel technique for solving a problem.
Every problem we will ever encounter was solved in the 1960s;
all we encounter is new variations of problems.
All we will ever do is create variations of solutions that already exist.
Whether or not you believe the statement above,
you are planning to do nothing new.
Everything you will ever want to do with a database has already been solved by Hibernate, MyBatis, and other JDBC tools.
Note that these are more than "just JDBC tools",
but they cover all of the JDBC stuff you will ever need or want to do.
Choose one of those and
read the documentation.
MyBatis is likely to be a good option,
since it is lighter weight than Hibernate.
I am using JAVA to create a log file, but after creating it, when I assert its existence, I get back a java.lang.AssertionError. I must be doing something simply wrong but I do not know what. Here is the code:
File testLogFile = new File("/home/ninad/eclipse-workspace/Log.txt");
testLogFile.createNewFile();
service = builder.withLogFile(testLogFile).build();
service.start
assertTrue(testLogFile.exists());
I can think of a few possible explanations:
You are not checking the result of the createNewFile() call. It returns true if the file did not exist before AND it has been successfully create.
By my reading of the javadoc, the method should throw an IOException if it tries to create the file and fails. But the flipside is that if you don't test the result of the call, you can't be sure that you got a new file.
The builder or the service could be removing or renaming the logfile.
If the code was part of a multi-threaded application, then another thread could have removed / renamed the file.
The file could (in theory) have been removed / renamed by another application.
You may have (OS-level) permission to create the file, but not test for its existence. (It seems a bit far-fetched ... but some OSes have "complicated" permissions systems.)
There could be other things I haven't thought of. If you provided an MCVE (including the "builder" implementation) we could check.
The goal with my program is to have it save when closed, and reloaded when opened.
I have a driver (which contains all of the graphics) and I want it to create and save a file. I've seen numerous tutorials on the internet, but what they fail to explain is how to correctly implement this system in an actual program.
Do I create the OutputStrema in my main method? Do I need to check if a file has been created and if not create one, and if so read from it? How do I accomplish all of this? Should I have a WindowListener for quitting so that it can save all of the data?
Thanks
Yes, a WindowListener sounds like a good idea. One way to save the state of a program is to use Properties. Please have a look at the tutorial linked to above. I'm not sure what to recommend for your "graphics". Please tell us more details about just what you mean here.
Edit
Do I create the OutputStrema in my main method?
you're question re creating the OutputStream in the main method is asking about program structure that we know nothing about. My gut tells me that i wouldn't create anything like this in the main method, even if the JFrame is created there (or in a static method called from main). The OutputStream would be created in the class that implements the WindowListener, and this can be its own stand alone class. You want to make the main method as small as possible.
Do I need to check if a file has been created and if not create one, and if so read from it?
Possibly. This question revolves around what you're going to do with the stored information once created. Perhaps you'll search for it and read it on program start up? I don't know as it all depends on your needs, something you'll have to figure out.
How do I accomplish all of this? Should I have a WindowListener for quitting so that it can save all of the data?
If this is a Swing application, then yes, a WindowListener would help you control your application's closing.
Do I create the OutputStrema in my main method?
It would be better to create the stream at the point where you are saving the state.
When my program runs it is going to take in the saved data file with its ObjectInputStream. Do I put the code to accomplish this in my Main method?
Sounds like a good choice. Basically, you need to do this before you attempt to do something that needs that data. Anything that achieves this will work (though doing it using static initialization is a bad idea ...)
Do I need to check if a file has been created and if not create one, and if so read from it?
This question is confusing writing the state file and reading it. They occur at different points in the lifecycle, and use different code to do the task.
There is no point checking to see if a save file exists before creating one ... unless you propose to rename the existing save file.
Conversely, if a save file doesn't exist when you start the application, then the constructor that attempts to open it will throw a FileNotFoundException. Just catch the exception and skip the code that reads the saved state.
... if there has not been a file created yet, will this cause an error?
Yes. A FileNotFoundException; see above. So your code has to deal with that, or test to see if the file exists before attempting to open in; see File.exists() and related methods.
Should I have a WindowListener for quitting so that it can save all of the data?
That sounds like part of the solution. (But what about the case where the program crashes or is killed? Do you want to save state in those cases ... or not?)
A couple of things to beware of:
Many GUI-related objects do not implement Serializable, and therefore cannot be saved using an ObjectOutputStream. Threads, streams, sockets and a few other things can't be serialized either.
When you save instances of classes using ObjectOutputStream, change the classes or their names, and then attempt to reload them using ObjectInputStream, you are liable to run into trouble with saved instances not matching the new versions of the classes. If you have to be able to read that serialized state you are in trouble.
Is there any way to programmatically differentiate between what caused an IOException? For example Java will throw an IOException, if there was an error during writing. How can I tell, if it's something like access violation, if the Disk is out of free space, if someone disconnected the the network drive, or other things?
I can't really parse the Message since, there does not seem to be any standardized message format, Sun (or Oracle now I guess) doesn't seem to have any sort of standardized format.
(I need to use Java to fix a very broken system at work.)
Unfortunately Java has no equivalent of .NET's System.Runtime.InteropServices.Marshal.GetHRForException(). You tell what kind of I/O error it was only if the exception is an instance of a subclass, e.g. FileNotFoundException.
Getting a hold of the exception's exact class will give you one of a handful of possible subclasses of IOException, and these are quite standardized. You can either test classes with instanceof or (a brutish approach) compare strings returned from getClass().getName().
There are some workarounds for the other stuff; you can do a File.canWrite() on a file you're about to open for writing (well, your program should have done that anyway, if the name and/or directory can vary), and if there's a chance you ran out of file space, you could try writing a small file to a known good location and seeing if that explodes on you. Not very elegant, I know: Java is not really known as a systems programming language.
On the other hand, very often knowing a detailed cause for an exception doesn't help much: With or without the knowledge, your user may simply not be able to get the program to do what's needed.