目录
4.利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码
一、转换流基本介绍
字符转换输入流:InputStreamReader 在Reader下
字符转换输出流:OutputStreamWriter 在Writer下
在JDK11中:
InputStreamReader被FileReader取代;
OutputStreamWriter被FileWriter取代
转换流的作用:
- 指定字符集读写数据(JDK11之后已经淘汰)
- 字节流想要使用字符流中的方法

二、转换流的使用
1.利用转换流按照指定字符编码读取
public class ConvertStreamDemo1 {
public static void main(String[] args) throws IOException {
// 该方法在JDK11已过时
/*InputStreamReader isr = new InputStreamReader(
new FileInputStream("chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfile.txt"),
"GBK");
int ch;
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
isr.close();*/
// 使用下面的方法读取文件
FileReader fr = new FileReader(
"chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfile.txt",
Charset.forName("GBK"));
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
}
}
运行结果:
2.利用转换流按照指定字符编码写出
public class ConvertStreamDemo2 {
public static void main(String[] args) throws IOException {
// 下面的方式在JDK11已过时
/*OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(
"chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfiletest.txt"),
"GBK");
osw.write("万紫千红总是春");
osw.close();*/
FileWriter fw = new FileWriter(
"chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfiletest1.txt",
Charset.forName("GBK"));
fw.write("万紫千红总是春");
fw.close();
}
}
3.将本地文件中的GBK文件,转成UTF-8
public class ConvertStreamDemo3 {
public static void main(String[] args) throws IOException {
/*InputStreamReader isr = new InputStreamReader(new FileInputStream("chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfile.txt"), "GBK");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("chapter18\\src\\com\\testdemo\\myconvertstream\\utf-8file.txt"), "UTF-8");
int ch;
while ((ch = isr.read()) != -1) {
osw.write(ch);
}
osw.close();
isr.close();*/
FileReader fr = new FileReader("chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfile.txt", Charset.forName("GBK"));
FileWriter fw = new FileWriter("chapter18\\src\\com\\testdemo\\myconvertstream\\utf-8file1.txt", Charset.forName("UTF-8"));
// 或者:
// FileWriter fw = new FileWriter("chapter18\\src\\com\\testdemo\\myconvertstream\\utf-8file.txt", StandardCharsets.UTF_8);
int ch;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
fw.close();
fr.close();
}
}
运行结果:
4.利用字节流读取文件中的数据,每次读一整行,而且不能出现乱码
public class ConvertStreamDemo4 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("chapter18\\src\\com\\testdemo\\myconvertstream\\gbkfile.txt");
InputStreamReader isr = new InputStreamReader(fis, "GBK");
BufferedReader br = new BufferedReader(isr);
String ch;
while ((ch = br.readLine()) != null) {
System.out.println(ch);
}
br.close();
}
}
运行结果:

8649

被折叠的 条评论
为什么被折叠?



