so I have an object, a Hotel, which implements Serializable. I am using an FX application that has many buttons. The FX application has a hotel object, as a field, which is the object that I want to read/write.
Is it read before write? or write before read? and should it be in the start method?
Do you have the read/write methods right next to each other on startup? Or should I have a button to close/save the application, and have it write the object to a file (and read it on startup)?
Here's what I have so far, and I believe it's writing successfully, but it is not reading.
#Override
public void start(Stage primaryStage) {
try {
ObjectOutputStream oosoos = new ObjectOutputStream(new FileOutputStream("hotelRooms.dat"));
oosoos.writeObject(hotel);
}catch (IOException e) {
System.out.println(e.getMessage());
}
// Hotel tempHotel;
try {
ObjectInputStream iisiis = new ObjectInputStream(new FileInputStream("hotelRooms.dat"));
hotel = (Hotel)iisiis.readObject();
} catch (IOException | ClassNotFoundException ffe ) {
System.out.println(ffe.getMessage());
}
I've never used FX before, but I think I might be able to help, by making some assumptions...
I assume that your start() method is a lifecycle method defined by some FX class and you need to load the Hotel object when the application starts. Presumably you then have some sort of finish() method where you want to save the latest version of the Hotel object for later..?
If so, you need to 'read()' the object in the start() method and 'write()' the Hotel in the finish() method.
The problem in your code snippet is that you are trying to do both in the start() method. This has all manner of potential issues, not least of which is that your write() method needs to flush the stream (causing the data to actually be written to the file) and you probably then need to close the output stream before the input stream will be allowed to read.
Probably.
It might just be that if you call
oosoos.close(); // this will flush the stream
...after
oosoos.writeObject(hotel);
then the intput stream will successfully read the object.
However, you really need to split this code up as I mentioned previously - the code that you have posted is pointless; you write the Hotel object to the file and then read it back... you could just use the object that you wrote to file, without ever reading it back in...
Hope this helps and apologies if I have misunderstood, due to lack of knowledge of FX.
What I did was split up the read/write. I have it so it reads/inputs on startup, and when they click a button to create a reservation, it writes the current hotel object to the file.
Related
According to this link, if the source has a problem when opening and throws an exception and it is also in try parentheses, JVM closes it. My question is how to inform the user now that this source is closed and we encountered a problem when opening this resource? In other words, how can this exception be handled?
Seems trivial. Usually, java code is running in some sort of 'no user interaction' environment (servers and the like). The right move is to let the exception bubble up - you want the daily job that is halfway through reading through the database to open the related file to then send the logs to long term storage or whatever it is to completely abort and write a note in the log file. Usually for jobs like that, there's some atomary functionality (in this case, perhaps each such file is independent of the others, and its okay to leave the 'broken' one in place for now until a server admin can look at it whilst continuing to process the remainder - in that case, the 'do the backup rotation thing on THIS file' is the atomary functionality): Catch all exceptions and write code that does what you want when the job fails. For example, my servers can send notifications straight to admin phones (via telegram or pushover, or using slack API, and there are many services that automate this for you too), if it's important, you'd write that in your catch block.
For code that is directly 'triggered' by a user, let's say a 'save file' function, then it's not so much 'the resource is now closed' - resources are not long lived (they cannot be - not if you use try-with-resources). They were either never open in the first place (you attempt to save a file to a dir that doesn't exist - the act of trying to make the new OutputStream already failed, it was never open to begin with), or, perhaps it did open, but it was to a USB stick and the user pulled it out halfway through saving. The resource is just closed, effectively, whether in java you .close() it or not - the entire stick is gone!!
The only thing the 'safe close' aspect of try-with-resources did for you is ensure that your Java Process isn't wasting a file handle.
You handle it the same way you handle pretty much any 'unrecoverable' (you can't write software that hypnotises the user into sticking that USB stick back into the machine, obviously - it is not recoverable as a consequence, like most exceptions) problem: You toss up a dialog box that explains the situation.
try (OutputStream out = Files.newOutputStream(saveGameFile)) {
boardState.save(out);
} catch (IOException e) {
// show dialog here
}
Even when using a try-with-resources, the catch clause still works.
private static void printFile() throws MyCustomException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
} catch (IOException e) {
throw new MyCustomException("There was an error while opening the resource", e);
}
}
I have a query on handling error conditions with Java Swing.
I am using Netbeans to develop a simple Java Swing app. It is to load in a text file, then run calculation based on the numbers found in the text file. The main Swing class holds the JFrames and JPanels.
I have the file loading code as a separate class file. It returns the number of lines read and a List of numbers back to the main Swing app.
I realised that if the file reading fails (i.e. try -> catch (Exception ex)), the entire app will crash. What's the best way to handle errors resulting from my scenario above? That is to say, the file loading code crashes and I don't want the entire program to crash. I want the program to say the file is corrupted and wait for user to load new file.
Any thoughts?
Yakult
when you catch the exception, run:
JOptionPane.showMessageDialog("File is corrupted. Please select a new file.");
Then display the file dialog again.
It's probably best to do this as a loop that continues while the the file is not valid. If there is a corruption, then rather than throwing an exception, set a boolean flag and loop as long as the flag is set. That way, when a good file is found, the while loop will terminate.
Example:
public static void main(String[] args){
boolean goodFile = false;
while (!goodFile){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog();
goodFile = processFile(chooser.getSelectedFile());
}
}
private boolean processFile(File file){
//do you stuff with the file
//return true if the processing works properly, and false otherwise
}
yeah
the problem is with your IO reading concept
the while loop is reading to the end of the file and so on..
to prevent that u can use a buffered reader
and use this code
String line = null
while((line = reader.readLine())!= null) {
// do stuf
}
if you are having this problem with processing the read line
all you need is to create a exception class of your own by extending Exception class and throw that exception in your catch block
after setting the message to your custom exception class you can set that message in to
JOptionPane.showMessageDialog(null,"message here"); //showMessageDialog is a static method
ok
You just catch the exception and put condition in the catch block. If the file contains other content that your application is intended to handle then you could call your method which will re-handle another file.
The main handling of your new process of the new file manipulation will start from your catch block. So in this way you are using java thrown exception to restart your application in a brand new way other than relaunching your app from the zero level.
Alright, so I created a Client and Server that manipulates a Map via a GUI interface using a text based protocol. The handler below was used to create a "work order" to manipulate the GUI on a separate thread from the network communications.
class RemoteInputHandler implements Runnable,SharedVariables
{
#Override
public void run()
{
try
{
String input = netComm.reader.readLine();
while (input != null)
{
// Make a separate copy of the input string
String inputCopy = input;
// Post a work order to process the command on the GUI thread
Platform.runLater(() ->
{
handleRemote(inputCopy);
});
// Get the next remote input
input = netComm.reader.readLine();
}
} catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
This pulls the next line of input from the server without freezing up the GUI. I then use the input in the handleRemote() method with a scanner to determine what is done with the input. The string retrieved from the reader looked something like "put key value". I'd then get the first word "put", using a scanner, to get the "command" and use a switch statement to determine how the GUI / Map should be updated on the client and server side respectively.
I'm doing another GUI based program that uses a binary protocol instead, but I'm having trouble figuring out how to handle the information in the same way as I did with the readLine() above. Is there a way to do this? Am i thinking about it the wrong way? I thought I could just get all of the bytes into an array, but I'm having trouble even figuring that out.
I could really use a hint! Thank you!
I have a query on handling error conditions with Java Swing.
I am using Netbeans to develop a simple Java Swing app. It is to load in a text file, then run calculation based on the numbers found in the text file. The main Swing class holds the JFrames and JPanels.
I have the file loading code as a separate class file. It returns the number of lines read and a List of numbers back to the main Swing app.
I realised that if the file reading fails (i.e. try -> catch (Exception ex)), the entire app will crash. What's the best way to handle errors resulting from my scenario above? That is to say, the file loading code crashes and I don't want the entire program to crash. I want the program to say the file is corrupted and wait for user to load new file.
Any thoughts?
Yakult
when you catch the exception, run:
JOptionPane.showMessageDialog("File is corrupted. Please select a new file.");
Then display the file dialog again.
It's probably best to do this as a loop that continues while the the file is not valid. If there is a corruption, then rather than throwing an exception, set a boolean flag and loop as long as the flag is set. That way, when a good file is found, the while loop will terminate.
Example:
public static void main(String[] args){
boolean goodFile = false;
while (!goodFile){
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog();
goodFile = processFile(chooser.getSelectedFile());
}
}
private boolean processFile(File file){
//do you stuff with the file
//return true if the processing works properly, and false otherwise
}
yeah
the problem is with your IO reading concept
the while loop is reading to the end of the file and so on..
to prevent that u can use a buffered reader
and use this code
String line = null
while((line = reader.readLine())!= null) {
// do stuf
}
if you are having this problem with processing the read line
all you need is to create a exception class of your own by extending Exception class and throw that exception in your catch block
after setting the message to your custom exception class you can set that message in to
JOptionPane.showMessageDialog(null,"message here"); //showMessageDialog is a static method
ok
You just catch the exception and put condition in the catch block. If the file contains other content that your application is intended to handle then you could call your method which will re-handle another file.
The main handling of your new process of the new file manipulation will start from your catch block. So in this way you are using java thrown exception to restart your application in a brand new way other than relaunching your app from the zero level.
I went through a java tutorial that allowed me to create a text file and write the words,"20 Bruce Wayne" in it. The last method that is called in the main class is named closeFile() that "closes" the text file after it is created.
Why does the file need to be "closed" if I didn't really open it? By "open", I mean the Notepad editor(not the IDE I'm using) pops up with the words "20 Bruce Wayne". Please answer my question in layman's terms.
Main.java:
class apple {
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
createfile.java
public class createfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("supermanvsbatman.txt");
}
catch(Exception e){
System.out.println("you have an error");
}
}
public void addRecords(){
x.format("%s%s%s","20 ", "Bruce ", "Wayne ");
}
public void closeFile(){
x.close();
}
}
When a file is "opened," the OS marks the file as locked, generally so it can't be deleted by other processes while it's being used. x.close() undoes the lock, allowing the OS and other processes to do what it wishes with the file.
In addition to the answer of Sold Out Activist, when you are working with i/o operations, such as files, you are using a stream to add text to your file, or extract text from your file. This stream must be closed, with the method close(), when you are exiting your program, because you could lose data. It's like a saving operation, if you don't save your file (close the stream), you will lose the changes made on file.
See this example, and this.
is used for closing the file which is opened in write mode because to reduce/to make secure our data we use close() method
and it throws exception like (java.io.IOEXCEPTION) why means any method call with respect to object only because it is public void close() that means it is instance so it is calls with respect with object so in some times is there a chance to getting object to get null any method calls with respect to null reference then it getting NullPointerException so this is the code
code in finally block means what ever files we open that and all relinquished in finally block
The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources. If the stream is already closed, it will have no effect.