explain the close() method in Java in Layman's terms - java

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.

Related

Reading/Writing Objects using Serializable

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.

error display in GUI [duplicate]

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.

FileChannel.tryLock sometimes throws AccessDeniedException

I've written a small method that is meant to tell me if another instance of the application is already running. I am aware that there are many ways to find out if another instance is running, but I chose this one. I am creating an empty file and keeping it locked for the duration of the application instance. If another instance is running, the tryLock() method is supposed to return null:
private static boolean alreadyRunning() throws IOException {
FileChannel fc = FileChannel.open(MYLOCKFILE,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.DELETE_ON_CLOSE);
return fc.tryLock() == null;
}
(MYLOCKFILE is a Path for a file in my temp directory.)
When testing this on Windows 7 Professional 64-bit, I found that it works as expected for the first instance and the second attempted instance. However, after the second instance exits (leaving just the first instance running), when a third instance is run, the tryLock() call throws java.nio.file.AccessDeniedException instead of returning null. Can you explain this behaviour? If this is considered normal behaviour, how can I differentiate between an existing instance having the file locked, and a real 'access denied' situation such as an idiot setting the TEMP directory to read-only?
I made a test project and tested the code the only problem because of which java.nio.file.AccessDeniedException is thrown is StandardOpenOption.DELETE_ON_CLOSE option used in the code.
I removed the option and it works fine now
FileChannel fc = FileChannel.open(MYLOCKFILE, StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
Explanation that I can think because of which java.nio.file.AccessDeniedException is thrown is that as soon as your second instance terminates the option StandardOpenOption.DELETE_ON_CLOSE [More explaination] will attempt to delete the file on JVM exit and failing might have registered an event in kernel or OS to delete the file as and when possible. So if any other process tries to access, create or write the same file before deletion it throws java.nio.file.AccessDeniedException as a delete operation is already pending for that file.
EDIT
As per your new comment, you can add the following code in try finally block placed after checking alreadyRunning() code.
Snippet Example:
if(!alreadyRunning())
{
try
{
// YOUR CODE THAT RUNS
while(true)
{
//YOUR
Thread.sleep(35000);
}
}
finally
{
new File("f:\\test.lock").deleteOnExit();
}
}

Error messages with Java Swing

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.

New/strange Java "try()" syntax?

While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I saw code as follows:
/**
* 'try-with-resources'
*/
class Example {
void foo() {
try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) {
}
}
}
I've never seen try used like this and I've been coding in Java for 9 years! Does any one know why you would do this? What is a possible use-case / benefit of doing this?
An other pieces of code I saw, I thought was a very useful shorthand so I'm sharing it here as well, it's pretty obvious what it does:
/**
* 'multi-catch'
*/
class Example {
void foo() {
try {
} catch (IllegalArgumentException | NullPointerException | ClassCastException e) {
e.printStackTrace();
}
}
}
It was added in Java 7. It's called the try-with-resources statement.
/edit
Might as well throw this in here too. You can use the try-with-resources statement to manage Locks if you use a wrapper class like this:
public class CloseableLock implements Closeable {
private final Lock lock;
private CloseableLock(Lock l) {
lock = l;
}
public void close() {
lock.unlock();
}
public static CloseableLock lock(Lock l) {
l.lock();
return new CloseableLock(l);
}
}
try(CloseableLock l = CloseableLock.lock(lock)) { // acquire the lock
// do something
} // release the lock
However, since you have to declare a variable for every resource, the advantage of this is debatable.
This is Java 7's new try-with-resources statement: http://download.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
Those are changes introduced in JDK7.
First statement is a try-with-resources. I don't know exactly why they exist but exceptions are often caused by inputstreams etc, I guess it just improves readability. Edit: thanks to the other answerers, I read the javadoc and I now know that it will close all i/o streams that implement AutoCloseable, omitting the need for a finally block in a lot of situations
Second is a multi-catch, which is really handy when you have different exceptions that you handle in exactly the same way.
Same usage as using(Resource) in C Sharp,which means this resource will be automatic recycled when your program has leaven out of this code block.(Just my opinion)
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource
The try-with-resources Statement
It's called try-with-resource. It's a way so as to not have to clean after yourself as the language will do it for you.
it was added in java 7. It is called try with resources. Try with resources statement feature was introduced in java 7 version. Try with resource statement is a try statement that declares one or more statements. A resource is an object that must be closed after the program is finished with it.
Before java 7 we use finally block to close the resources that we have used in our program. In finally block we have to close all the resources manually that we have used in our program.
For more information you can visit try with resources
That is called with a try with resources. in a try with resources, any kind of closable stream declared in the resources section will be closed after the try statement is done. So it pretty much is a
try{
InputStream is;
//Stuff
}finally{
is.close()
}
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Categories

Resources