本文主要内容:
(1)字符型文件输入流
(2)字符型文件输出流
1.读取中文可能会产生问题,例子如下:
public class Test4 {
public static void main(String[] args) {
//字节输入流,读取中文可能会产生问题
//字节流的好处在于什么类型的文件都可以处理,不好在于处理纯文本的文件
//可能会产生乱码的问题
try {
FileInputStream fis = new FileInputStream(new File("D://test//Test.txt"));
byte[] b = new byte[5];
int count = fis.read(b);
while (count!=-1){
String s = new String(b,0,count);
System.out.println(s);
count = fis.read(b);
}
System.out.println("打印完毕");
//我�
//�欢�
//��abc
//打印完毕
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.字符型文件输入流(FileReader)
(1)java.io包
(2)继承于InputStreamReader、Reader
(3)构造方法:带file的构造方法
(4)常用方法:
read();read(char[]);close();
public class Test5 {
public static void main(String[] args) {
FileReader fr = null;
try {
File file = new File("D://test//Test.txt");
fr = new FileReader(file);
int code = fr.read();
while (code!=-1){
System.out.println((char)code);
code = fr.read();
}
System.out.println("完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.字符型文件输出流(FileWriter)
(1)java.io包
(2)继承于OutPutStreamWriter、Writer
(3)构造方法:带file参数、带file、boolean参数、带String参数、带String、boolean参数
(4)常用方法:
write(int);write(char[]);write(String);flush();close();
public class Test6 {
public static void main(String[] args) {
FileWriter fw = null;
try {
File file = new File("D://test//Test.txt");
fw = new FileWriter(file);
char[] ch = {'我','喜','欢','你'};
fw.write(ch);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}