Created
August 20, 2020 06:51
-
-
Save jamesBan/033e16d86228be1158525916e6a4ee26 to your computer and use it in GitHub Desktop.
切割、合并文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class File | |
* @package app\commands | |
*/ | |
class File | |
{ | |
/** | |
* @param string $filename | |
* @param int $length | |
* @return array | |
*/ | |
public static function split(string $filename, int $length) | |
{ | |
$parts = []; | |
$handle = new \SplFileObject($filename, 'r'); | |
$index = 0; | |
while ($content = $handle->fread($length)) { | |
$extension = '.' . $handle->getExtension(); | |
$filename = $handle->getPath(). DIRECTORY_SEPARATOR . | |
$handle->getBasename($extension) . '-' . $index . | |
$extension; | |
$f = fopen($filename, 'w+'); | |
fwrite($f, $content); | |
fclose($f); | |
$parts[] = [ | |
'file_path' => $filename, | |
'md5' => md5_file($filename), | |
]; | |
$index++; | |
} | |
return $parts; | |
} | |
/** | |
* @param string $filename | |
* @param mixed ...$fileParts | |
* @return array | |
*/ | |
public static function merge(string $filename, ...$fileParts) | |
{ | |
$fileHandle = new \SplFileObject($filename, 'w+'); | |
foreach ($fileParts as $part) { | |
$handle = new \SplFileObject($part, 'r'); | |
//read 256KB | |
while ($content = $handle->fread(1024 * 256)) { | |
$fileHandle->fwrite($content); | |
} | |
$handle = null; | |
} | |
$fileHandle = null; | |
return [ | |
'file_path' => $filename, | |
'md5' => md5($filename) | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment