设为首页 加入收藏

TOP

Java IO流 之 字符流
2016-12-12 08:15:28 】 浏览:8431
Tags:Java 字符

字符流 :读的也是二进制文件,他会帮我们解码成我们看的懂的字符。
字符流 = 字节流 + 解码


(一)字符输入流: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();
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java IO流 复制图片 下一篇Java 缓冲流 Buffer

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目