public abstract class FileObject extends Object implements Serializable, Lookup.Provider
Modifier and Type | Field and Description |
---|---|
static String |
DEFAULT_LINE_SEPARATOR_ATTR
Name of default line separator attribute.
|
static String |
DEFAULT_PATHNAME_SEPARATOR_ATTR
Name of default path name separator attribute.
|
Constructor and Description |
---|
FileObject() |
Modifier and Type | Method and Description |
---|---|
abstract void |
addFileChangeListener(FileChangeListener fcl)
Add new listener to this object.
|
void |
addRecursiveListener(FileChangeListener fcl)
Adds a listener to this
FileObject and all its children and
children or its children. |
byte[] |
asBytes()
Reads the full content of the file object and returns it as array of
bytes.
|
List<String> |
asLines()
Reads the full content of the file line by line with default
system encoding.
|
List<String> |
asLines(String encoding)
Reads the full content of the file line by line.
|
String |
asText()
Reads the full content of the file object and returns it as string.
|
String |
asText(String encoding)
Reads the full content of the file object and returns it as string.
|
boolean |
canRead()
Tests if this file can be read.
|
boolean |
canRevert()
Checks whether this file can be reverted to a pristine state.
|
boolean |
canWrite()
Tests if this file can be written to.
|
FileObject |
copy(FileObject target,
String name,
String ext)
Copies this file.
|
OutputStream |
createAndOpen(String name)
Creates new file in this folder and immediately opens it for writing.
|
FileObject |
createData(String name)
Create new data file in this folder with the specified name.
|
abstract FileObject |
createData(String name,
String ext)
Create new data file in this folder with the specified name.
|
abstract FileObject |
createFolder(String name)
Create a new folder below this one with the specified name.
|
void |
delete()
Delete this file.
|
abstract void |
delete(FileLock lock)
Delete this file.
|
boolean |
existsExt(String ext)
Test whether there is a file with the same basename and only a changed extension in the same folder.
|
protected void |
fireFileAttributeChangedEvent(Enumeration<FileChangeListener> en,
FileAttributeEvent fe)
Fire file attribute change event.
|
protected void |
fireFileChangedEvent(Enumeration<FileChangeListener> en,
FileEvent fe)
Fire file change event.
|
protected void |
fireFileDataCreatedEvent(Enumeration<FileChangeListener> en,
FileEvent fe)
Fire data creation event.
|
protected void |
fireFileDeletedEvent(Enumeration<FileChangeListener> en,
FileEvent fe)
Fire file deletion event.
|
protected void |
fireFileFolderCreatedEvent(Enumeration<FileChangeListener> en,
FileEvent fe)
Fire folder creation event.
|
protected void |
fireFileRenamedEvent(Enumeration<FileChangeListener> en,
FileRenameEvent fe)
Fire file rename event.
|
abstract Object |
getAttribute(String attrName)
Get the file attribute with the specified name.
|
abstract Enumeration<String> |
getAttributes()
Get all file attribute names for this file.
|
FileObject |
getCanonicalFileObject()
Return a FileObject with path where all symbolic links are resolved.
|
abstract FileObject[] |
getChildren()
Get all children of this folder (files and subfolders).
|
Enumeration<? extends FileObject> |
getChildren(boolean rec)
Enumerate all children of this folder.
|
Enumeration<? extends FileObject> |
getData(boolean rec)
Enumerate all data files in this folder.
|
abstract String |
getExt()
Get the extension of this file or folder.
|
FileObject |
getFileObject(String relativePath)
Retrieve file or folder relative to a current folder, with a given relative path.
|
abstract FileObject |
getFileObject(String name,
String ext)
Retrieve file or folder contained in this folder by name.
|
abstract FileSystem |
getFileSystem()
Get the filesystem containing this file.
|
Enumeration<? extends FileObject> |
getFolders(boolean rec)
Enumerate the subfolders of this folder.
|
abstract InputStream |
getInputStream()
Get input stream.
|
Lookup |
getLookup()
A lookup containing various logical views of the underlying represented file.
|
String |
getMIMEType()
Get the MIME type of this file.
|
String |
getMIMEType(String... withinMIMETypes)
Resolves MIME type from the list of acceptable ones.
|
abstract String |
getName()
Get the name without extension of this file or folder.
|
String |
getNameExt()
Getter for name and extension of a file object.
|
OutputStream |
getOutputStream()
Get output stream.
|
abstract OutputStream |
getOutputStream(FileLock lock)
Get output stream.
|
String |
getPackageName(char separatorChar)
Deprecated.
Please use the ClassPath API instead.
|
String |
getPackageNameExt(char separatorChar,
char extSepChar)
Deprecated.
Please use the ClassPath API instead.
|
abstract FileObject |
getParent()
Get parent folder.
|
String |
getPath()
Get the full resource path of this file object starting from the filesystem root.
|
abstract long |
getSize()
Get the size of the file.
|
URL |
getURL()
Deprecated.
Use
FileObject.toURL() instead. |
boolean |
hasExt(String ext)
Test whether this file has the specified extension.
|
abstract boolean |
isData()
Test whether this object is a data object.
|
abstract boolean |
isFolder()
Test whether this object is a folder.
|
boolean |
isLocked()
Test if file is locked
|
abstract boolean |
isReadOnly()
Deprecated.
Please use the
FileObject.canWrite() . |
abstract boolean |
isRoot()
Test whether this object is the root folder.
|
boolean |
isSymbolicLink()
Check whether this FileObject is a symbolic link.
|
abstract boolean |
isValid()
Test whether the file is valid.
|
boolean |
isVirtual()
Tests if file really exists or is missing.
|
abstract Date |
lastModified()
Get last modification time.
|
abstract FileLock |
lock()
Lock this file.
|
FileObject |
move(FileLock lock,
FileObject target,
String name,
String ext)
Moves this file.
|
FileObject |
readSymbolicLink()
Read symbolic link.
|
String |
readSymbolicLinkPath()
Read symbolic link path.
|
void |
refresh()
Should check for external modifications.
|
void |
refresh(boolean expected)
Should check for external modifications.
|
abstract void |
removeFileChangeListener(FileChangeListener fcl)
Remove listener from this object.
|
void |
removeRecursiveListener(FileChangeListener fcl)
Removes listener previously added by
FileObject.addRecursiveListener(org.openide.filesystems.FileChangeListener) |
abstract void |
rename(FileLock lock,
String name,
String ext)
Renames this file (or folder).
|
void |
revert()
Revert this file to a pristine state.
|
abstract void |
setAttribute(String attrName,
Object value)
Set the file attribute with the specified name.
|
abstract void |
setImportant(boolean b)
Deprecated.
No longer used. Instead use
SharabilityQuery . |
String |
toString()
Gets a textual represtentation of this
FileObject . |
URI |
toURI()
Gets a URI for this file.
|
URL |
toURL()
Get URL that can be used to access this file.
|
public static final String DEFAULT_LINE_SEPARATOR_ATTR
System.getProperty("line.separator")
. Call
fo.getAttribute(DEFAULT_LINE_SEPARATOR_PROP)
returns string with
default line separator. Default line separator will be used by the text
editor if saving new content to an initially empty file. Any other code
which creates file content programmatically must manually read this
property if it cares.public static final String DEFAULT_PATHNAME_SEPARATOR_ATTR
File.separator
. Call
fo.getAttribute(DEFAULT_PATHNAME_SEPARATOR_ATTR)
returns string with
default separator.public abstract String getName()
public abstract String getExt()
public abstract void rename(FileLock lock, String name, String ext) throws IOException
Note that using this call, it is currently only possible to rename within
a parent folder, and not to do moves across folders.
Conversely, implementing filesystems need only implement "simple" renames.
If you wish to move a file across folders, you should call FileUtil.moveFile(org.openide.filesystems.FileObject, org.openide.filesystems.FileObject, java.lang.String)
.
lock
- File must be locked before renaming.name
- new basename of fileext
- new extension of file (ignored for folders)IOException
public FileObject copy(FileObject target, String name, String ext) throws IOException
target
- target folder to move this file toname
- new basename of fileext
- new extension of file (ignored for folders)IOException
public FileObject move(FileLock lock, FileObject target, String name, String ext) throws IOException
lock
- File must be locked before renaming.target
- target folder to move this file toname
- new basename of fileext
- new extension of file (ignored for folders)IOException
public String toString()
FileObject
.
The precise format is not defined. In particular it is probably
not a resource path.
For that purpose use FileObject.getPath()
directly.
Typically it is useful for debugging purposes. Example of correct usage:
FileObject fo = getSomeFileObject(); ErrorManager.getDefault().log("Got a change from " + fo);
public String getPath()
Subclasses are strongly encouraged to override this method.
Never use this to get a display name for the file! Use FileUtil.getFileDisplayName(org.openide.filesystems.FileObject)
.
Do not use this method to find a file path on disk! Use FileUtil.toFile(org.openide.filesystems.FileObject)
.
FileSystem.findResource(java.lang.String)
@Deprecated public String getPackageNameExt(char separatorChar, char extSepChar)
separatorChar
.
The extension, if present, is separated from the basename with extSepChar
.
Note: fo.getPath() will have the same effect as using this method with / and . (the standard path and extension delimiters).
separatorChar
- char to separate folders and filesextSepChar
- char to separate extension@Deprecated public String getPackageName(char separatorChar)
FileObject.getPackageNameExt(char, char)
but omits the extension.separatorChar
- char to separate folders and filespublic String getNameExt()
public abstract FileSystem getFileSystem() throws FileStateInvalidException
Note that it may be possible for a stale file object to exist which refers to a now-defunct filesystem. If this is the case, this method will throw an exception.
FileStateInvalidException
- if the reference to the file
system has been lost (e.g., if the filesystem was deleted)public abstract FileObject getParent()
FileObject.isFolder()
.null
if this object FileObject.isRoot()
.public abstract boolean isFolder()
public abstract Date lastModified()
public abstract boolean isRoot()
public abstract boolean isData()
FileObject.isFolder()
.public abstract boolean isValid()
public boolean existsExt(String ext)
FileObject.getFileObject(String name, String ext)
.ext
- the alternate extensionpublic abstract void delete(FileLock lock) throws IOException
lock
- the lock obtained by a call to FileObject.lock()
IOException
- if the file could not be deletedpublic final void delete() throws IOException
IOException
- if the file could not be deleted or
FileAlreadyLockedException if the file is already locked FileObject.lock()
public Lookup getLookup()
this
FileObject
(however not necessarily only one, possibly more). The identity of the
lookup should survive
move operation
- the resulting FileObject
after successful move
will share the same Lookup
as the original FileObject
.
That is why one can put fileObject.getLookup()
into
IdentityHashMap
<Lookup,Anything>
and cache
Anything
regardless the actual location of (moved) file.
Or one can obtain a Lookup.Result
from the Lookup
, keep
its reference, attach a listener to it and be assured that it
will fire events even if the file gets renamed.
Inside of NetBeans Platform application the content of this lookup is usually
identical to the one provided by the
DataObject.find(this).getLookup()
.
This functionality is provided by the org.netbeans.modules.settings
module.
DataObject.move
operation preserves the object's identity, and to mimic the same behavior
without reference to
DataObject
the behavior of FileObject.getLookup()
has
been modelled.
getLookup
in interface Lookup.Provider
public abstract Object getAttribute(String attrName)
attrName
- name of the attributenull
if the attribute is unset (or could not be properly restored for some reason)public abstract void setAttribute(String attrName, Object value) throws IOException
FileObject.getAttribute(java.lang.String)
method.
setAttribute
method. One can use
prefix methodvalue:
or newvalue:
to store references to
Method or
Class respectively.
The meaning is then similar to XMLFileSystem
attributes
methodvalue
and newvalue
.
attrName
- name of the attributevalue
- new value or null
to clear the attribute. Must be serializable, although particular filesystems may or may not use serialization to store attribute values.IOException
- if the attribute cannot be set. If serialization is used to store it, this may in fact be a subclass such as NotSerializableException
.public abstract Enumeration<String> getAttributes()
public final boolean hasExt(String ext)
ext
- the extension the file should have.
) is equal to the given extensionpublic abstract void addFileChangeListener(FileChangeListener fcl)
fcl
- the listenerpublic abstract void removeFileChangeListener(FileChangeListener fcl)
fcl
- the listenerpublic void addRecursiveListener(FileChangeListener fcl)
FileObject
and all its children and
children or its children.
It is guaranteed that whenever a change
is made via the FileSystem API itself under this FileObject
that it is notified to the fcl
listener. Whether external
changes (if they make sense) are detected and
notified depends on actual implementation. As some implementations may
need to perform non-trivial amount of work during initialization of
listeners, this methods can take long time. Usage of this method may
consume a lot of system resources and as such it shall be used with care.
Traditional FileObject.addFileChangeListener(org.openide.filesystems.FileChangeListener)
is definitely preferred variant.
If you are running with the MasterFS module enabled, it guarantees
that for files backed with real File
, the system initializes
itself to detect external changes on the whole subtree.
This requires non-trivial amount of work and especially on slow
disks (aka networks ones) may take a long time to add the listener
and also refresh the system when FileObject.refresh()
and especially FileUtil.refreshAll()
is requested.
fcl
- the listener to registerpublic void removeRecursiveListener(FileChangeListener fcl)
FileObject.addRecursiveListener(org.openide.filesystems.FileChangeListener)
fcl
- the listener to removeprotected void fireFileDataCreatedEvent(Enumeration<FileChangeListener> en, FileEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectprotected void fireFileFolderCreatedEvent(Enumeration<FileChangeListener> en, FileEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectprotected void fireFileChangedEvent(Enumeration<FileChangeListener> en, FileEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectprotected void fireFileDeletedEvent(Enumeration<FileChangeListener> en, FileEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectprotected void fireFileAttributeChangedEvent(Enumeration<FileChangeListener> en, FileAttributeEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectprotected void fireFileRenamedEvent(Enumeration<FileChangeListener> en, FileRenameEvent fe)
en
- listeners that should receive the eventfe
- the event to fire in this objectpublic String getMIMEType()
java.awt.datatransfer
package.
The default implementation calls FileUtil.getMIMEType(java.lang.String)
.
(As a fallback return value, content/unknown
is used.)
"text/plain"
; never null
public String getMIMEType(String... withinMIMETypes)
FileUtil.getMIMEType(org.openide.filesystems.FileObject, java.lang.String[])
,
but subclasses may override this method to be more effective.withinMIMETypes
- A hint to the underlaying infrastructure to
limit the search to given array of MIME types.null
if
the FileObject is unrecognized. It may return content/unknown
instead of null
.
It is possible for the resulting MIME type to not be a member of given withinMIMETypes
list.public abstract long getSize()
public abstract InputStream getInputStream() throws FileNotFoundException
FileNotFoundException
- if the file does not exists, is a folder
rather than a regular file or is invalidpublic byte[] asBytes() throws IOException
IOException
- in case the content cannot be fully readpublic String asText(String encoding) throws IOException
encoding
- the encoding to useIOException
- in case the content cannot be fully readpublic String asText() throws IOException
FileObject.asText(java.lang.String)
with
default system encoding.IOException
- in case the content cannot be fully readpublic List<String> asLines() throws IOException
for
loops:
for (String line : fo.asLines()) { // do something }
The list is optimized for iterating line by line, other operations, like accessing all the lines or counting the number of its lines may be suboptimal.
IOException
- in case the content cannot be fully readpublic List<String> asLines(String encoding) throws IOException
for
loops:
for (String line : fo.asLines("UTF-8")) { // do something }
The list is optimized for iterating line by line, other operations, like accessing all the lines or counting the number of its lines may be suboptimal.
encoding
- the encoding to useIOException
- in case the content cannot be fully readpublic abstract OutputStream getOutputStream(FileLock lock) throws IOException
lock
- the lock that belongs to this file (obtained by a call to
FileObject.lock()
)IOException
- if an error occures (the file is invalid, etc.)public final OutputStream getOutputStream() throws FileAlreadyLockedException, IOException
IOException
- if an error occurs (the file is invalid, etc.)FileAlreadyLockedException
- if the file is already lockedpublic abstract FileLock lock() throws IOException
FileAlreadyLockedException
- if the file is already lockedIOException
- (UserQuestionException) in case when the lock cannot be obtained now,
but the underlaying implementation is able to do it after some
complex/dangerous/long-lasting operation and request confirmation
from the userpublic boolean isLocked()
@Deprecated public abstract void setImportant(boolean b)
SharabilityQuery
.
For example: Java sources have important .java
files and
unimportant .class
files. If the filesystem provides
an "archive" feature it should archive only .java
files.
b
- true if the file should be considered importantpublic abstract FileObject[] getChildren()
FileObject.getChildren(boolean)
,
FileObject.getFolders(boolean)
,
FileObject.getData(boolean)
public Enumeration<? extends FileObject> getChildren(boolean rec)
rec
- whether to enumerate recursivelyFileObject
public Enumeration<? extends FileObject> getFolders(boolean rec)
rec
- whether to recursively list subfoldersFileObject
(satisfying FileObject.isFolder()
)public Enumeration<? extends FileObject> getData(boolean rec)
rec
- whether to recursively search subfoldersFileObject
(satisfying FileObject.isData()
)public abstract FileObject getFileObject(String name, String ext)
name
- basename of the file or folder (in this folder)ext
- extension of the file; null
or ""
if the file should have no extension or if folder is requestednull
if the file
or folder does not existIllegalArgumentException
- if this
is not a folderpublic FileObject getFileObject(String relativePath)
relativePath
- is just basename of the file or (since 4.16) the relative path delimited by '/'null
if the file
or folder does not existIllegalArgumentException
- if this
is not a folderpublic abstract FileObject createFolder(String name) throws IOException
FileChangeListener.fileFolderCreated(org.openide.filesystems.FileEvent)
.name
- the name of folder to create. Periods in name are allowed (but no slashes).IOException
- if the folder cannot be created (e.g. already exists), or if this
is not a folderFileUtil.createFolder(java.io.File)
public abstract FileObject createData(String name, String ext) throws IOException
FileChangeListener.fileDataCreated(org.openide.filesystems.FileEvent)
.name
- the name of data object to create (can contain a period, but no slashes)ext
- the extension of the file (or null
or ""
)IOException
- if the file cannot be created (e.g. already exists), or if this
is not a folderFileUtil.createData(java.io.File)
public FileObject createData(String name) throws IOException
FileChangeListener.fileDataCreated(org.openide.filesystems.FileEvent)
.name
- the name of data object to create (can contain a period, but no slashes)IOException
- if the file cannot be created (e.g. already exists), or if this
is not a folderFileUtil.createData(java.io.File)
public OutputStream createAndOpen(String name) throws IOException
FileObject.createData(java.lang.String)
method.
Using that method
makes it
possible for someone to read the content of the newly created
file before its content is written. This method does its best to eliminate
such race condition.
This method usually delivers both, data created
and changed
events. Preferably it delivers them asynchronously. The assumption
is that the file will be (at least partially) written before
the listeners start to process the first event. The safety is additionally
ensured by mutual exclusion
between output and input streams
for the same file (any call to FileObject.getInputStream()
will be blocked
for at least two seconds if there is existing open output stream).
If you finish writing the content of your file in those two seconds,
you can be sure, nobody will have read its content yet.
name
- name of file to create with its extensionIOException
- if the file cannot be created (e.g. already exists), or if this
is not a folder@Deprecated public abstract boolean isReadOnly()
FileObject.canWrite()
.The value returned from this method should indicate the capabilities of the file from the point of view of users of the FileObject's API, the actual state of the file on a disk does not matter if the implementation of the filesystem can change it when requested.
The result returned from this method should be tight together with
the expected behaviour of getOutputStream
. If it is
likely that the method successfully returns a stream that can be
written to, let the isReadOnly
return false
.
Also other fileobject methods like delete
are suggested to be connected to result of this method. If not
read only, then it can be deleted, etc.
It is a good idea to call this method before attempting to perform any operation on the FileObject that might throw an IOException simply because it is read-only. If isReadOnly returns true, the operation may be skipped, or the user notified that it cannot be done. However it is often desirable for the user to be able to continue the operation in case the filesystem supports making a file writable. In this case calling code should:
FileObject.lock()
and catch any exception thrown.
UserQuestionException#confirmed
on it
(asynchronously - do not block any important threads). If true
,
proceed with the operation. If false
, exit.
If an IOException
is thrown, notify it and exit.
IOException
is thrown, call FileObject.isReadOnly()
.
If true
, ignore the exception (it is expected).
If false
, notify it.
true
if file is read-onlypublic boolean canWrite()
The default implementation simply uses java.io.File.canWrite
if there exists conversion to java.io.File
(see FileUtil.toFile(org.openide.filesystems.FileObject)
).
If conversion is not possible, then deprecated method FileObject.isReadOnly()
is used.
public boolean canRead()
The default implementation simply uses java.io.File.canRead
if there exists conversion to java.io.File
(see FileUtil.toFile(org.openide.filesystems.FileObject)
).
If conversion is not possible, then true
is returned.
public final boolean canRevert()
FileObject.revert()
might do somethingpublic final void revert() throws IOException
FileObject.canRevert()
is false, does nothing.
Note that while content can be reset, it may not be possible to reset attributes.
Implementors: for historical reasons this method checks FileObject.getAttribute(java.lang.String)
for a special attribute named removeWritables
which must be of type
Callable
. If present, the file is considered modified.
IOException
public void refresh(boolean expected)
expected
- should the file events be marked as expected change or not?FileEvent.isExpected()
public void refresh()
The file events are marked as unexpected.
@Deprecated public final URL getURL() throws FileStateInvalidException
FileObject.toURL()
instead.FileStateInvalidException
- neverpublic final URL toURL()
URLMapper.findURL(org.openide.filesystems.FileObject, int)
,
URLMapper.INTERNAL
public final URI toURI()
FileObject.toURL()
.public boolean isVirtual()
public boolean isSymbolicLink() throws IOException
IOException
- If some I/O problem occurs.public FileObject readSymbolicLink() throws IOException
IOException
- If some I/O problem occurs.public String readSymbolicLinkPath() throws IOException
IOException
- If some I/O problem occurs.public FileObject getCanonicalFileObject() throws IOException
IOException
- If some I/O problem occurs.