Home > Article > Backend Development > [PHP] Return to the basics (IO stream), return to the io_PHP tutorial
IO stream is used to handle data transfer between devices
java operates on data through streams
javaObjects used to operate streams are in the IO package
Streams are divided into two types according to operation data: byte stream and character stream
Streams are divided into: input stream, output stream
Character stream
Abstract base class: Reader Writer
File operation, write
Get the FileWriter object, new comes out, construction parameters: String file name ; At this time, a file will be created in the specified directory. If it already exists, it will be overwritten; this method will throw IOExceptionException
Call the FileWriter object's write() method to write the string into the stream, parameters: StringString
Call the FileWriter object's flush() method to refresh the stream
FileWriter fw=<span>new</span> FileWriter("test.txt"<span>); fw.write(</span>"hello3"<span>); fw.close();</span><span>//</span><span>刷新并关闭</span>
File operation, read
Get the FileReader object, new come out, construction parameters: String file name
Call the read() method of the FileReader object to return the read length. If it reaches the end, it will return -1, parameter: char[] Character array
while loop reading, condition: if the read length is not -1
Combined string
FileReader fr=<span>new</span> FileReader("test.txt"<span>); </span><span>char</span>[] buf=<span>new</span> <span>char</span>[2<span>]; </span><span>int</span> len=0<span>; StringBuilder sb</span>=<span>new</span><span> StringBuilder(); </span><span>while</span>((len=fr.read(buf))!=-1<span>){ sb.append(</span><span>new</span> String(buf,0<span>,len)); } System.out.println(sb.toString());</span>
PHP version, file operation, writing
Call the function fopen() to open the file and obtain the file object, parameters: String file name, "w" is written, if the file does not exist, it will be created
Call the fwrite() method to write directly to the file. Parameters: file object, String string
Call the fclose() method to close the stream, parameters: file object
<span>$file</span>=<span>fopen</span>("test.txt","w"<span>); </span><span>fwrite</span>(<span>$file</span>,"hello"<span>); </span><span>fclose</span>(<span>$file</span>);
File operation, read
Call the function fopen() to open the file and get the file object, parameters: String file name, ”r” reads
Call the function fread() to get the string of String, parameters: fileObject, read length
while loop reading, condition: not to the end of the file, feof($file) is not true
Concatenate strings
<span>$file</span>=<span>fopen</span>("test.txt","r"<span>); </span><span>$str</span>=""<span>; </span><span>while</span>(!<span>feof</span>(<span>$file</span><span>)){ </span><span>$str</span>.=<span>fread</span>(<span>$file</span>, 1<span>); } </span><span>echo</span> <span>$str</span><span>; </span><span>fclose</span>(<span>$file</span>);