Home >php教程 >php手册 >[PHP] 重回基础(IO流),重回io

[PHP] 重回基础(IO流),重回io

WBOY
WBOYOriginal
2016-06-13 08:40:011598browse

[PHP] 重回基础(IO流),重回io

IO流用来处理设备之间的数据传输

java对数据的操作是通过流的方式

java用于操作流的对象都在IO包中

流按操作数据分为两种:字节流与字符流

流按流向分为:输入流,输出流

 

字符流

抽象基类:Reader Writer

 

文件操作,写

获取FileWriter对象,new出来,构造参数:String的文件名;此时会在指定目录下创建出文件,如果已存在,将会被覆盖;这个方法会抛出IOException异常

调用FileWriter对象的write()方法,将字符串写入到流中,参数:String字符串

调用FileWriter对象的flush()方法,刷新流

        FileWriter fw=<span>new</span> FileWriter("test.txt"<span>);
        fw.write(</span>"hello3"<span>);
        fw.close();</span><span>//</span><span>刷新并关闭</span>

 

 

文件操作,读

获取FileReader对象,new出来,构造参数:String的文件名

调用FileReader对象的read()方法,返回读取的长度,如果到末尾会返回-1,参数:char[] 字符数组

while循环读取,条件:如果读取的长度不为-1

组合字符串

        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版,文件操作,写 

调用函数fopen(),打开文件获取file对象,参数:String的文件名,”w”写入,如果文件不存在会创建

调用fwrite()方法,直接就写到文件里去了,参数:file对象,String的字符串

调用fclose()方法,关闭流,参数:file对象

 

<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>);

 

文件操作,读

调用函数fopen(),打开文件获取file对象,参数:String的文件名,”r”读取

调用函数fread(),得到String的字符串,参数:file对象,读取长度

while循环读取,条件:没有到文件末尾,feof($file)不为true

拼接字符串

<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>);

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn