Java Reference
In-Depth Information
Opening Folders
You cannot create folders directly. The only constructor is protected. Instead, you get a
Folder
from a
Session
, a
Store
, or another
Folder
like this:
Folder
outbox
=
container
.
getFolder
(
"sent-mail"
);
There are actually three
getFolder()
methods, one each in the
Session
,
Store
, and
Folder
classes. They all have the same signature and behave similarly:
public
abstract
Folder
getFolder
(
String
name
)
throws
MessagingException
These methods share an annoying idiosyncrasy with the
File
class. Getting a
Folder
object doesn't imply that the named
Folder
actually exists on the server. To tell whether
the folder is really present, you have to test for it with the
exists()
method:
public
boolean
exists
()
throws
MessagingException
When you first get a folder, it's closed. Before you can read the messages it contains, you
have to open the folder using the
open()
method:
public
abstract
void
open
(
int
mode
)
throws
FolderNotFoundException
,
MessagingException
The
mode
argument should be one of the two named constants,
Folder.READ_ONLY
or
Folder.READ_WRITE
. Some but not all implementations allow you to open multiple
connections to one real folder using multiple
Folder
objects.
Some operations discussed in this section, such as searching or retrieving messages from
a folder, can only be performed on an open folder. Others, such as deleting or changing
the name of a folder, can only be done to a closed folder. The
isOpen()
method returns
true
if the folder is open,
false
if it's closed:
public
abstract
boolean
isOpen
()
Generally, trying to do something with a closed folder that requires the folder to be open
or vice versa will throw a
java.lang.IllegalStateException
. This is a runtime ex‐
ception, so it doesn't need to be explicitly caught or declared.
When you're done with a folder, close it using the
close()
method:
public
abstract
void
close
(
boolean
expunge
)
throws
FolderNotFoundException
,
MessagingException
If the
expunge
argument is
true
, any deleted messages in the folder are deleted from
the actual file on the server. Otherwise, they're simply marked as deleted, but the mes‐
sages can still be undeleted.
Folder
does not implement
AutoCloseable
so even in Java 7 you may want to use the
dispose pattern to close a folder in a
finally
block. You'll want to check both that the
folder is not null and that it's open.