歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java IO流 之 字符流

Java IO流 之 字符流

日期:2017/3/1 9:08:29   编辑:Linux編程

字符流 :讀的也是二進制文件,他會幫我們解碼成我們看的懂的字符。
字符流 = 字節流 + 解碼

(一)字符輸入流:Reader : 它是字符輸入流的根類 ,是抽象類

  FileReader :文件字符輸入流 ,讀取字符串。
用法:
1.找到目標文件
2.建立數據的通道
3.建立一個緩沖區
4.讀取數據
5.關閉資源。

(二)字符流輸出流: Writer : 字符輸出流的根類 ,抽象的類
FileWiter :文件數據的輸出字符流
使用注意點:
    1.FileReader內部維護了一個1024個字符的數組,所以在寫入數據的時候,它是現將數據寫入到內部的字符數組中。

      如果需要將數據寫入到硬盤中,需要用到flush()或者關閉或者字符數組數據存滿了。
    2.如果我需要向文件中追加數據,需要使用new FileWriter(File , boolean)構造方法 ,第二參數true
    3.如果指定的文件不存在,也會自己創建一個。

字符輸出流簡單案例

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class fileWriter {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
testFileWriter();

}

public static void testFileWriter() throws IOException{

//1.找目標文件
File file = new File("D:\\a.txt");
//2.建立通道
FileWriter fwt = new FileWriter(file,true); //在文件後面繼續追加數據
//3.寫入數據(直接寫入字符)
fwt.write("繼續講課");
//4.關閉數據
fwt.close();
}
}

字符輸入流簡單案例

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class fileReader {

public static void main(String[] args) throws IOException {

//testFileReader();
testFileReader2();
}
//(1)輸入字符流的使用 這種方式效率太低。
public static void testFileReader() throws IOException{

//1.找目標文件
File file = new File("D:\\a.txt");

//2.建立通道
FileReader frd = new FileReader(file);

//3.讀取數據
int content = 0; //讀取單個字符。效率低
while ((content = frd.read()) != -1) {
System.out.print((char)content);
}

//4.關閉流
frd.close();
}

//(2)
public static void testFileReader2() throws IOException{

//1.找目標文件
File file = new File("D:\\a.txt");

//2.建立通道
FileReader frd = new FileReader(file);

//3.建立一個緩沖區 ,字符數組
char[] c = new char[1024];
int length = 0;

//4.讀取數據
while ((length = frd.read(c))!= -1) {
//字符串輸出
System.out.println(new String(c,0,length));
}
//5.關閉資源
frd.close();
}
}

Copyright © Linux教程網 All Rights Reserved