Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## com.trolltech.qt.core
Class QFile

    java.lang.Object
      com.trolltech.qt.internal.QSignalEmitterInternal
          com.trolltech.qt.QSignalEmitter
              com.trolltech.qt.QtJambiObject
                  com.trolltech.qt.core.QObject
                      com.trolltech.qt.core.QIODevice
                          com.trolltech.qt.core.QFile

All Implemented Interfaces:
  QtJambiInterface

Direct Known Subclasses:
  QTemporaryFile

    public class QFile

extends QIODevice

The QFile class provides an interface for reading from and writing to files. QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a `QTextStream` or `QDataStream`.

The file name is usually passed in the constructor, but it can be set at any time using `setFileName()`. QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.

You can check for a file's existence using `exists()`, and remove a file using `remove()`. (More advanced file system related operations are provided by `QFileInfo` and `QDir`.)

The file is opened with `open()`, closed with `close()`, and flushed with `flush()`. Data is usually read and written using `QDataStream` or `QTextStream`, but you can also call the `QIODevice`-inherited functions `read()`, `readLine()`, `readAll()`, `write()`. QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.

The size of the file is returned by size(). You can get the current file position using `pos()`, or move to a new file position using `seek()`. If you've reached the end of the file, atEnd() returns true.

## Reading Files Directly

The following example reads a text file line by line:

            QFile file = new QFile("in.txt");
            if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
                                                  QIODevice.OpenModeFlag.Text)))
                return;

            while (!file.atEnd()) {
                QByteArray line = file.readLine();
                process_line(line);
            }

The `QIODevice::Text` flag passed to `open()` tells Qt to convert Windows-style line terminators ("\r\n") into C++-style terminators ("\n"). By default, QFile assumes binary, i.e. it doesn't perform any conversion on the bytes stored in the file.

## Using Streams to Read Files

The next example uses `QTextStream` to read a text file line by line:

            QFile file = new QFile("in.txt");
            if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
                                                  QIODevice.OpenModeFlag.Text)))
                return;

            QTextStream in = new QTextStream(file);
            while (!in.atEnd()) {
                String line = in.readLine();
                process_line(line);
            }

`QTextStream` takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system's local 8-bit encoding is used (e.g., ISO 8859-1 for most of Europe; see `QTextCodec::codecForLocale()` for details). This can be changed using setCodec().

To write text, we can use operator<<(), which is overloaded to take a `QTextStream` on the left and various data types (including QString) on the right:

            QFile file = new QFile("out.txt");
            if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
                                                  QIODevice.OpenModeFlag.Text)))
                return;

            QTextStream out = new QTextStream(file);
            out.writeString("The magic number is: " + 49 + "\n");

`QDataStream` is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.

When you use QFile, `QFileInfo`, and `QDir` to access the file system with Qt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to use standard C++ APIs (`<cstdio>` or `<iostream>`) or platform-specific APIs to access files instead of QFile, you can use the `encodeName()` and `decodeName()` functions to convert between Unicode file names and 8-bit file names.

On Unix, there are some special system files (e.g. in `/proc`) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling `read()`. In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call `readAll()`, or call `read()` or `readLine()` repeatedly until no more data can be read. The next example uses `QTextStream` to read `/proc/modules` line by line:

            QFile file = new QFile("/proc/modules");
            if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
                                                  QIODevice.OpenModeFlag.Text)))
                return;

            QTextStream in = new QTextStream(file);
            String line = in.readLine();
            while (line != null) {
                process_line(line);
                line = in.readLine();
            }

## Signals

Unlike other `QIODevice` implementations, such as `QTcpSocket`, QFile does not emit the `aboutToClose()` , `bytesWritten()` , or `readyRead()` signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms.

## Platform Specific Issues

File permissions are handled differently on Linux/Mac OS X and Windows. In a non `writable` directory on Linux, files cannot be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.

See also:
  `QTextStream`, `QDataStream`, `QFileInfo`, `QDir`, and The Qt Resource System.

Nested Class Summary
`static class` | `QFile.FileError` This enum describes the errors that may be returned by the `error()` function.
`static class` | `QFile.MemoryMapFlags` This enum describes special options that may be used by the map() function.
`static class` | `QFile.Permission` This enum is used by the permission() function to report the permissions and ownership of a file.
`static class` | `QFile.Permissions`

Nested classes/interfaces inherited from class com.trolltech.qt.core.QIODevice
`QIODevice.OpenMode, QIODevice.OpenModeFlag`

Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
`QSignalEmitter.AbstractSignal, QSignalEmitter.Signal0, QSignalEmitter.Signal1, QSignalEmitter.Signal2, QSignalEmitter.Signal3, QSignalEmitter.Signal4, QSignalEmitter.Signal5, QSignalEmitter.Signal6, QSignalEmitter.Signal7, QSignalEmitter.Signal8, QSignalEmitter.Signal9`

Nested classes/interfaces inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`com.trolltech.qt.internal.QSignalEmitterInternal.AbstractSignalInternal`

Field Summary

Fields inherited from class com.trolltech.qt.core.QIODevice
`aboutToClose, bytesWritten, readChannelFinished, readyRead`

Fields inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`currentSender`

Constructor Summary
`QFile(QObject parent)` Constructs a new file object with the given `parent`.
`QFile(java.lang.String name)` Constructs a new file object to represent the file with the given `name`.
`QFile(java.lang.String name, QObject parent)` Constructs a new file object with the given `parent` to represent the file with the specified `name`.

Method Summary
`boolean` | `copy(java.lang.String newName)` Copies the file currently specified by `fileName()` to a file called `newName`.
`static boolean` | `copy(java.lang.String fileName, java.lang.String newName)` Copies the file `fileName` to `newName`.
`static java.lang.String` | `decodeName(QByteArray localFileName)` This does the reverse of `QFile::encodeName()` using `localFileName`.
`static java.lang.String` | `decodeName(java.lang.String localFileName)` Returns the Unicode version of the given `localFileName`.
`static QByteArray` | `encodeName(java.lang.String fileName)` By default, this function converts `fileName` to the local 8-bit encoding determined by the user's locale.
`QFile.FileError` | `error()` Returns the file error status.
`boolean` | `exists()` Returns true if the file specified by `fileName()` exists; otherwise returns false.
`static boolean` | `exists(java.lang.String fileName)` Returns true if the file specified by `fileName` exists; otherwise returns false.
`java.lang.String` | `fileName()` Returns the name set by `setFileName()` or to the QFile constructors.
`boolean` | `flush()` Flushes any buffered data to the file.
`int` | `handle()` Returns the file handle of the file.
`boolean` | `link(java.lang.String newName)` Creates a link named `linkName` that points to the file currently specified by `fileName()`.
`static boolean` | `link(java.lang.String oldname, java.lang.String newName)` Creates a link named `linkName` that points to the file `fileName`.
`boolean` | `open(int fd, QIODevice.OpenMode flags)` Opens the existing file descripter `fd` in the given `mode`.
`boolean` | `open(int fd, QIODevice.OpenModeFlag[] flags)`
`boolean` | `open(QIODevice.OpenMode flags)` Opens the file using OpenMode`mode`, returning true if successful; otherwise false.
`QFile.Permissions` | `permissions()` Returns the complete OR-ed together combination of `QFile::Permission` for the file.
`static QFile.Permissions` | `permissions(java.lang.String filename)` Returns the complete OR-ed together combination of `QFile::Permission` for `fileName`.
`boolean` | `remove()` Removes the file specified by `fileName()`.
`static boolean` | `remove(java.lang.String fileName)` Removes the file specified by the `fileName` given.
`boolean` | `rename(java.lang.String newName)` Renames the file currently specified by `fileName()` to `newName`.
`static boolean` | `rename(java.lang.String oldName, java.lang.String newName)` Renames the file `oldName` to `newName`.
`boolean` | `resize(long sz)` Sets the file size (in bytes) `sz`.
`static boolean` | `resize(java.lang.String filename, long sz)` Sets `fileName` to size (in bytes) `sz`.
`void` | `setFileName(java.lang.String name)` Sets the `name` of the file.
`boolean` | `setPermissions(QFile.Permission[] permissionSpec)`
`boolean` | `setPermissions(QFile.Permissions permissionSpec)` Sets the permissions for the file to the `permissions` specified.
`static boolean` | `setPermissions(java.lang.String filename, QFile.Permission[] permissionSpec)`
`static boolean` | `setPermissions(java.lang.String filename, QFile.Permissions permissionSpec)` Sets the permissions for `fileName` file to `permissions`.
`java.lang.String` | `symLinkTarget()` Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link.
`static java.lang.String` | `symLinkTarget(java.lang.String fileName)` Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by `fileName`, or returns an empty string if the `fileName` does not correspond to a symbolic link.
`void` | `unsetError()` Sets the file's error to `QFile::NoError` .

Methods inherited from class com.trolltech.qt.core.QIODevice
`atEnd, bytesAvailable, bytesToWrite, canReadLine, close, errorString, getByte, isOpen, isReadable, isSequential, isTextModeEnabled, isWritable, open, openMode, peek, peek, pos, putByte, read, read, readAll, readData, readLine, readLine, readLine, readLineData, reset, seek, setErrorString, setOpenMode, setOpenMode, setTextModeEnabled, size, ungetByte, waitForBytesWritten, waitForReadyRead, write, write, writeData`

Methods inherited from class com.trolltech.qt.core.QObject
`childEvent, children, connectSlotsByName, customEvent, disposeLater, dumpObjectInfo, dumpObjectTree, dynamicPropertyNames, event, eventFilter, findChild, findChild, findChild, findChildren, findChildren, findChildren, findChildren, indexOfProperty, installEventFilter, isWidgetType, killTimer, moveToThread, objectName, parent, properties, property, removeEventFilter, setObjectName, setParent, setProperty, startTimer, timerEvent, toString, userProperty`

Methods inherited from class com.trolltech.qt.QtJambiObject
`dispose, disposed, equals, finalize, reassignNativeResources, tr, tr, tr`

Methods inherited from class com.trolltech.qt.QSignalEmitter
`blockSignals, disconnect, disconnect, signalsBlocked, signalSender, thread`

Methods inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`__qt_signalInitialization`

Methods inherited from class java.lang.Object
`clone, getClass, hashCode, notify, notifyAll, wait, wait, wait`

Methods inherited from interface com.trolltech.qt.QtJambiInterface
`disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership`

Constructor Detail

### QFile

    public QFile(QObject parent)

  Constructs a new file object with the given `parent`.

### QFile

    public QFile(java.lang.String name)

  Constructs a new file object to represent the file with the given `name`.

### QFile

    public QFile(java.lang.String name,
                 QObject parent)

  Constructs a new file object with the given `parent` to represent the file with the specified `name`.

Method Detail

### copy

    public final boolean copy(java.lang.String newName)

  Copies the file currently specified by `fileName()` to a file called `newName`. Returns true if successful; otherwise returns false.

  Note that if a file with the name `newName` already exists, `copy()` returns false (i.e. QFile will not overwrite it).

  The source file is closed before it is copied.

See also:
  `setFileName()`.

### error

    public final QFile.FileError error()

  Returns the file error status.

  The I/O device status returns an error code. For example, if `open()` returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed.

See also:
  `unsetError()`.

### exists

    public final boolean exists()

  Returns true if the file specified by `fileName()` exists; otherwise returns false.

See also:
  `fileName()`, and `setFileName()`.

### fileName

    public final java.lang.String fileName()

  Returns the name set by `setFileName()` or to the QFile constructors.

See also:
  `setFileName()`, and `QFileInfo::fileName()`.

### flush

    public final boolean flush()

  Flushes any buffered data to the file. Returns true if successful; otherwise returns false.

### handle

    public final int handle()

  Returns the file handle of the file.

  This is a small positive integer, suitable for use with C library functions such as fdopen() and fcntl(). On systems that use file descriptors for sockets (i.e. Unix systems, but not Windows) the handle can be used with `QSocketNotifier` as well.

  If the file is not open, or there is an error, `handle()` returns -1.

  This function is not supported on Windows CE.

See also:
  `QSocketNotifier`.

### link

    public final boolean link(java.lang.String newName)

  Creates a link named `linkName` that points to the file currently specified by `fileName()`. What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

  This function will not overwrite an already existing entity in the file system; in this case, `link()` will return false and set `error()` to return `RenameError` .

  Note: To create a valid link on Windows, `linkName` must have a `.lnk` file extension.

See also:
  `setFileName()`.

### open

    public final boolean open(int fd,
                              QIODevice.OpenModeFlag[] flags)

### open

    public final boolean open(int fd,
                              QIODevice.OpenMode flags)

  Opens the existing file descripter `fd` in the given `mode`. Returns true if successful; otherwise returns false.

  When a QFile is opened using this function, `close()` does not actually close the file.

  The QFile that is opened using this function is automatically set to be in raw mode; this means that the file input/output functions are slow. If you run into performance issues, you should try to use one of the other open functions.

  Warning: If `fd` is 0 (`stdin`), 1 (`stdout`), or 2 (`stderr`), you may not be able to `seek()`. size() is set to `LLONG_MAX` (in `<climits>`).

  Warning: For Windows CE you may not be able to call `seek()`, setSize(), fileTime(). size() is set to `0`.

  Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a `QFileInfo`.

See also:
  `close()`.

### permissions

    public final QFile.Permissions permissions()

  Returns the complete OR-ed together combination of `QFile::Permission` for the file.

See also:
  `setPermissions()`, and `setFileName()`.

### remove

    public final boolean remove()

  Removes the file specified by `fileName()`. Returns true if successful; otherwise returns false.

  The file is closed before it is removed.

See also:
  `setFileName()`.

### rename

    public final boolean rename(java.lang.String newName)

  Renames the file currently specified by `fileName()` to `newName`. Returns true if successful; otherwise returns false.

  If a file with the name `newName` already exists, `rename()` returns false (i.e., QFile will not overwrite it).

  The file is closed before it is renamed.

See also:
  `setFileName()`.

### resize

    public final boolean resize(long sz)

  Sets the file size (in bytes) `sz`. Returns true if the file if the resize succeeds; false otherwise. If `sz` is larger than the file currently is the new bytes will be set to 0, if `sz` is smaller the file is simply truncated.

See also:
  size(), and `setFileName()`.

### setFileName

    public final void setFileName(java.lang.String name)

  Sets the `name` of the file. The name can have no path, a relative path, or an absolute path.

  Do not call this function if the file has already been opened.

  If the file name has no path or a relative path, the path used will be the application's current directory path at the time of the open() call.

  Example:

              QFile file = new QFile();
              QDir.setCurrent("/tmp");
              file.setFileName("readme.txt");
              QDir.setCurrent("/home");
              file.open(QIODevice.OpenModeFlag.ReadOnly);      // opens "/home/readme.txt" under Unix

  Note that the directory separator "/" works for all operating systems supported by Qt.

See also:
  `fileName()`, `QFileInfo`, and `QDir`.

### setPermissions

    public final boolean setPermissions(QFile.Permission[] permissionSpec)

### setPermissions

    public final boolean setPermissions(QFile.Permissions permissionSpec)

  Sets the permissions for the file to the `permissions` specified. Returns true if successful, or false if the permissions cannot be modified.

See also:
  `permissions()`, and `setFileName()`.

### symLinkTarget

    public final java.lang.String symLinkTarget()

  Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link.

  This name may not represent an existing file; it is only a string. `QFile::exists()` returns true if the symlink points to an existing file.

See also:
  `fileName()`, and `setFileName()`.

### unsetError

    public final void unsetError()

  Sets the file's error to `QFile::NoError` .

See also:
  `error()`.

### open

    public boolean open(QIODevice.OpenMode flags)

  Opens the file using OpenMode`mode`, returning true if successful; otherwise false.

  The `mode` must be `QIODevice::ReadOnly` , `QIODevice::WriteOnly` , or `QIODevice::ReadWrite` . It may also have additional flags, such as `QIODevice::Text` and `QIODevice::Unbuffered` .

  Note: In `WriteOnly` or `ReadWrite` mode, if the relevant file does not already exist, this function will try to create a new file before opening it.

  Note: Because of limitations in the native API, QFile ignores the Unbuffered flag on Windows.

See also:
  QIODevice::OpenMode, and `setFileName()`.

  Overrides:
    `open` in class `QIODevice`

### copy

    public static boolean copy(java.lang.String fileName,
                               java.lang.String newName)

  Copies the file `fileName` to `newName`. Returns true if successful; otherwise returns false.

  If a file with the name `newName` already exists, `copy()` returns false (i.e., QFile will not overwrite it).

See also:
  `rename()`.

### decodeName

    public static java.lang.String decodeName(QByteArray localFileName)

  This does the reverse of `QFile::encodeName()` using `localFileName`.

See also:
  setDecodingFunction(), and `encodeName()`.

### encodeName

    public static QByteArray encodeName(java.lang.String fileName)

  By default, this function converts `fileName` to the local 8-bit encoding determined by the user's locale. This is sufficient for file names that the user chooses. File names hard-coded into the application should only use 7-bit ASCII filename characters.

See also:
  `decodeName()`, and setEncodingFunction().

### exists

    public static boolean exists(java.lang.String fileName)

  Returns true if the file specified by `fileName` exists; otherwise returns false.

### link

    public static boolean link(java.lang.String oldname,
                               java.lang.String newName)

  Creates a link named `linkName` that points to the file `fileName`. What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

See also:
  `link()`.

### permissions

    public static QFile.Permissions permissions(java.lang.String filename)

  Returns the complete OR-ed together combination of `QFile::Permission` for `fileName`.

### remove

    public static boolean remove(java.lang.String fileName)

  Removes the file specified by the `fileName` given.

  Returns true if successful; otherwise returns false.

See also:
  `remove()`.

### rename

    public static boolean rename(java.lang.String oldName,
                                 java.lang.String newName)

  Renames the file `oldName` to `newName`. Returns true if successful; otherwise returns false.

  If a file with the name `newName` already exists, `rename()` returns false (i.e., QFile will not overwrite it).

See also:
  `rename()`.

### resize

    public static boolean resize(java.lang.String filename,
                                 long sz)

  Sets `fileName` to size (in bytes) `sz`. Returns true if the file if the resize succeeds; false otherwise. If `sz` is larger than `fileName` currently is the new bytes will be set to 0, if `sz` is smaller the file is simply truncated.

See also:
  `resize()`.

### setPermissions

    public static boolean setPermissions(java.lang.String filename,
                                         QFile.Permission[] permissionSpec)

### setPermissions

    public static boolean setPermissions(java.lang.String filename,
                                         QFile.Permissions permissionSpec)

  Sets the permissions for `fileName` file to `permissions`.

### symLinkTarget

    public static java.lang.String symLinkTarget(java.lang.String fileName)

  Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by `fileName`, or returns an empty string if the `fileName` does not correspond to a symbolic link.

  This name may not represent an existing file; it is only a string. `QFile::exists()` returns true if the symlink points to an existing file.

### decodeName

    public static java.lang.String decodeName(java.lang.String localFileName)

  Returns the Unicode version of the given `localFileName`. See encodeName() for details.

Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD