Java IO流 -> 节点流 -> 文件字符流
1. 文件字符流 FileReader/FileWriter
- FileReader:通过字符的方式读取文件,仅适合字符文件。
- FileWriter:通过字符的方式写出或追加数据到文件,仅适合字符文件。
import java.io.*;
public class TestFileReader {
public static void main(String[] args) {
Reader in = null;
try {
in = new FileReader("D:\\JavaAno\\code\\JavaSE\\基础语法\\src\\com\\io\\endpoint\\TestFileReader.java");
char[] buf = new char[10];
for(int len = -1; (len = in.read(buf)) != -1; len++){
System.out.print(new String(buf, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(in != null){
in.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
import java.io.*;
public class TestFileWriter {
public static void main(String[] args) {
Writer out = null;
try {
out = new FileWriter("outWriter.txt");
String str = "I am studying FileWriter.\n(我在学习文件字符输出流)";
char[] buf = str.toCharArray();
out.write(buf);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(out != null){
out.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
2. 追加数据
out = new FileWriter("outWriter.txt", true);