-
Notifications
You must be signed in to change notification settings - Fork 0
topics.io
[ [doc://topics/io I/O Basics] | [doc://topics/iocollections Collections] | [doc://topics/streams Streams] ]
The [class://io.File File] class represents a file in the file system.
with ($f= new File('/etc', 'passwd')); {
$f->open(FILE_MODE_READ);
while ($line= $f->readLine()) {
// ...
}
$f->close();
}
with ($f= new File('name.txt')); {
$f->open(FILE_MODE_WRITE);
$f->write('Timm'."\n");
$f->close();
}
with ($f= new File('names.txt')); {
$f->open(FILE_MODE_APPEND);
$f->write('Timm'."\n");
$f->close();
}
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');
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
}
The [class://io.Folder 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):
$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!
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();
}