您的位置:首页 > 其它

IO流第七课,字符流、纯文本、节点流,Reader、FileReader、Writer、FileWriter读取、写出、拷贝

2015-03-30 13:49 495 查看
字符流:只能处理纯文本,全部为可见字符,后缀为.txt和.html

节点流  Reader   FileReader

             Writer    FileWriter

一、纯文本读取四个步骤

建立联系
选择流   Reader   FileReader
读取 char[] c = new char[1024];
关闭
package com.pkushutong.ioFile;

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

public class Test09 {
public static void main(String[] args) {
// 创建文件源
File src = new File("F:/FileTest/demo.txt");

Reader r = null;
// 选择流
try {
r = new FileReader(src);
char[] c = new char[1024];
int len = 0;

while((len = r.read(c)) != -1){
//字符数组转字符串
String str = new String(c,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
}finally{
if(r != null){
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


二、纯文本写出

建立联系
选择流   Writer    FileWriter
读取 writer(字符数组,0,长度)+flush;
关闭
package com.pkushutong.ioFile;

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

public class Text10 {
public static void main(String[] args) {
// 创建文件源
File src = new File("F:/FileTest/demo.txt");

Writer w = null;
try {
w = new FileWriter(src);
String msg = "默认自动提取您文章\r\n的前200字显示在博客\t首页作为文章摘要";
w.write(msg);
w.append("的分公司分点给山东饭馆大发光火收到个");

w.flush();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(w != null){
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐