Skip to content
Alex Kiesel edited this page May 26, 2012 · 7 revisions

I/O: Basics

[ [doc://topics/io I/O Basics] | [doc://topics/iocollections Collections] | [doc://topics/streams Streams] ]

Files

The [class://io.File File] class represents a file in the file system.

Reading a file

with ($f= new File('/etc', 'passwd')); { $f->open(FILE_MODE_READ); while ($line= $f->readLine()) { // ... } $f->close(); }

Writing a file

with ($f= new File('name.txt')); { $f->open(FILE_MODE_WRITE); $f->write('Timm'."\n"); $f->close(); }

Appending a file

with ($f= new File('names.txt')); { $f->open(FILE_MODE_APPEND); $f->write('Timm'."\n"); $f->close(); }

FileUtil

Alternatively, the [class://io.FileUtil FileUtil] class can be used to get and set the entire file contents at once:

// Read words.txt's contents into a string $words= FileUtil::getContents(new File('words.txt'));

// Write the string 'Timm' to a file called name.txt FileUtil::putContents(new File('name.txt'), 'Timm');

Exceptions

All of the above methods will throw [class://io.IOException IOException]s or subclasses of that on failure. So the above examples could be rewritten to handle errors gracefully as follows:

try { $words= FileUtil::getContents(new File('words.txt')); } catch (FileNotFoundException $fe) { // File 'words.txt' was not found } catch (IOException $ie) { // Read error, permission denied }

Folders

The [class://io.Folder Folder] class represents a folder in the file system.

Iterating over a folder's contents

The following will yield all files and folders inside the /home folder except the well-known entries "." (current directory) and ".." (parent directory):

$f= new Folder('/home/thekid'); while ($e= $f->getEntry()) { // ... e= "bin" (directory, test with is_dir()) // ... e= "bug12.patch" (file), test with is_file()) // ... (etc.) }

Note: The [doc://topics/iocollections I/O Collections API] offers a way more flexible approach!

Example: a temporary folder

This will create a folder named 'work' in the system's temporary directory and remove it once we're finished working with it.

with ($work= new Folder(System::tempDir(), 'work')); {
// Create only if it doesn't already exist yet.
$work->exists() || $work->create();

// ... work with the folder

// Remove the folder and all of its contents recursively
$work->unlink();

}

Clone this wiki locally