IO流的体系及FileReader、FileWriter
生活随笔
收集整理的這篇文章主要介紹了
IO流的体系及FileReader、FileWriter
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package IOStream;import org.junit.Test;import java.io.File;
import java.io.FileReader;
import java.io.IOException;public class FileReadWriter {//@Testpublic void testFileReader() {
// fr需要提前聲明FileReader fr = null;
// 1.實例化File類的對象,指明要操作的文件try {File file1 = new File("hello.txt");// 2.提供具體的流:(找到管道)fr = new FileReader(file1);// 3.數(shù)據(jù)的讀入
// read()返回讀入的一個字符,用int 接受的時ASCII碼,如果達(dá)到末尾則返回-1
// 方式1:
// int data = fr.read();
// while(data != -1){
// System.out.print((char) data);
// data = fr.read();
// }
// 方式2:int data ;while((data = fr.read())!= -1){System.out.print((char)data);}} catch (IOException e) {e.printStackTrace();} finally {try {if(fr!=null){fr.close();}} catch (IOException e) {e.printStackTrace();}}// 4.流的關(guān)閉操作}
}
read()的重載方法:read(char cbuffer[])? 返回的是讀入的字符個數(shù)
// 對read()操作方法的一個升級:使用read重載方法// read(char[]) 返回每次讀入的字符個數(shù),比如helloworld123!,會返回5 5 4 -1@Testpublic void testFileReader2() { // 1.File類的實例化FileReader fr = null;try {File file = new File("hello.txt");// 2.流的實例化fr = new FileReader(file); // 3.讀入操作 // read(char[]) 返回每次讀入的字符個數(shù),比如helloworld123!,會返回5 5 4 -1char[] cbuffer = new char[5];int len ;while((len = fr.read(cbuffer))!=-1){for(int i = 0 ; i < len; i++){System.out.print(cbuffer[i]);}}} catch (IOException e) {e.printStackTrace();} finally {try { // 4.資源關(guān)閉if (fr != null) {fr.close();}} catch (IOException e) {e.printStackTrace();}}}FileWriter的說明:
package IOStream; /* 從內(nèi)存中寫出數(shù)據(jù)到硬盤里 說明: 1.輸出操作中File對象可以不存在,會自動創(chuàng)建此文件若存在,在構(gòu)造器中append:選擇true為在后面繼續(xù)添加,false為覆蓋原文件FileWriter(file,true/false) 2.*/ import org.junit.Test;import java.io.File; import java.io.FileWriter; import java.io.IOException;public class FileWriterTest {@Testpublic void testFileWriter() throws IOException { // 1.提供File對象,指明寫出的文件File file1 = new File("hello1.txt");// 2.提供FileWriter對象,用于數(shù)據(jù)的寫出FileWriter fw = new FileWriter(file1,false);// 3.寫出的操作fw.write("i have a dream!\n");fw.write("you need to have a dream!");// 4.流資源的關(guān)閉fw.close();} }總結(jié)
以上是生活随笔為你收集整理的IO流的体系及FileReader、FileWriter的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php利用ajax文件上传,如何在PHP
- 下一篇: mysql limit asc_MySq