日志文章

2019-12-23 aflfte2011

文本文件的读写(Reader,Wirter的使用)

package com.aflfte.IO;

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

/**
 * 文件字符输入流
 * 流程:
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、释放资源
 * @author jinhao
 *
 */

public class Test07 {
public static void main(String[] args) {
//创建源
File f=new File("src/abc.txt");
//选择流
Reader read=null;
try {
read=new FileReader(f);
//操作(分段读取);
char[] flush=new char[1024];
int len=-1;
try {
while((len=read.read(flush))!=-1) {
String temp=new String(flush,0,len);
System.out.println(temp);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(read!=null) {
try {
read.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}


package com.aflfte.IO;

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

/**
 * 文件字符输出流
 * 流程:
 * 1、创建源
 * 2、选择流
 * 3、操作(写入)
 * 4、释放资源
 * @author jinhao
 *
 */
public class Test08 {
public static void main(String[] args) {
File f=new File("str.txt");
Writer w=null;
try {
w=new FileWriter(f);
String a="世界多么美好";
//写入方法一:
char[] wr=a.toCharArray();
w.write(wr);
//写入方法二
w.write(a);
//写入方法三
w.append("Hello Word!").append("世界多么美好");
w.flush();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
if(w!=null) {
try {
w.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

}

}
}

« IO字节数组输入流与输出流的使用 | IO写入文件»