forked from xp-framework/xp-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
topics.io
Alex Kiesel edited this page Jun 7, 2012
·
7 revisions
The io.File
class represents a file in the file system.
<?php
with ($f= new File('/etc', 'passwd')); {
$f->open(FILE_MODE_READ);
while ($line= $f->readLine()) {
// ...
}
$f->close();
}
?>
<?php
with ($f= new File('name.txt')); {
$f->open(FILE_MODE_WRITE);
$f->write('Timm'."\n");
$f->close();
}
?>
<?php
with ($f= new File('names.txt')); {
$f->open(FILE_MODE_APPEND);
$f->write('Timm'."\n");
$f->close();
}
?>
Alternatively, the io.FileUtil
class can be used to
get and set the entire file contents at once:
<?php
// 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');
?>
All of the above methods will throw io.IOException
s or
subclasses of that on failure. So the above examples could be rewritten to
handle errors gracefully as follows:
<?php
try {
$words= FileUtil::getContents(new File('words.txt'));
} catch (FileNotFoundException $fe) {
// File 'words.txt' was not found
} catch (IOException $ie) {
// Read error, permission denied
}
?>
The io.Folder
class represents a folder in the file system.
The following will yield all files and folders inside the /home
folder except the well-known entries "."
(current directory)
and ".."
(parent directory):
<?php
$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 I/O Collections API offers a way more flexible approach!
This will create a folder named 'work' in the system's temporary directory and remove it once we're finished working with it.
<?php
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();
}
?>