转换流
当我们的文件里面含有中文英文数字时,我们使用字节流将文件内容在内存中显示,英文和数字显示正常,而中文却却显示乱码。这时候我们可以使用转换流将其转化为字符流显示在内存中。
转换流:InputStreamReader 、OutputStreamWriter提供了在字节流和字符流之间的转换。
InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
转换流的作用,文本文件在硬盘中以字节流的形式存储时,通过InputStreamReader读取后转化为字符流给程序处理,程序处理的字符流通过OutputStreamWriter转换为字节流保存。
转换流的特点:
其是字符流和字节流之间的桥梁。
可对读取到的字节数据经过指定编码转换成字符。
可对读取到的字符数据经过指定编码转换成字节。
何时使用转换流?
当字节和字符之间有转换动作时;
流操作的数据需要编码或解码时;
InputStreamReader、OutputStreamWriter 要InputStream或OutputStream作为参数,实现从字节流到字符流的转换。
作用:提供字节流与字符流之间的转换,很多时候我们使用转换流来处理文件乱码问题,实现编码和解码的功能。
解码:字节,字节数组 –》 字符,字符数组
编码:字符,字符数组 –》 字节,字节数组
InputStreamReader
InputStreamReader实现将字节的输入流按指定字符集转换为字符的输入流。
需要和InputStream“套接”。
构造器:
InputStreamReader(InputStream in) 创建一个使用默认字符集的 InputStreamReader。
InputStreamReader(InputStream in, String charsetName) 创建使用指定字符集的 InputStreamReader。
示例代码:
import java.io.*;
public class InputStreamReaderTest {
public static void main(String[] args) {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream(new File("d:/io/hello_gbk.txt"));
// 使用系统默认的字符集(utf-8),发现乱码
// isr = new InputStreamReader(fis);
// 参数二指明字符集具体使用哪个字符集取决于文件.txt保存时使用哪个字符集
isr = new InputStreamReader(fis, "gbk");
char[] cbuf = new char[1024];
int len;
while ((len = isr.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字符集:utf-8,gbk…
当一个文本文件时以gbk字符集存储时,我们使用utf-8字符集去转换会查看到乱码,所以要清楚看查看文本内容,要转换为文件保存时使用的字符集。
OutputStreamWriter
OutputStreamWriter实现将字符的输出流按指定字符集转换为字节的输出流。
需要和OutputStream“套接”。
构造器:
OutputStreamWriter(OutputStream out) 创建使用默认字符编码的 OutputStreamWriter。
OutputStreamWriter(OutputStream out, String charsetName) 创建使用指定字符集的 OutputStreamWriter。
接下来,我们使用InputStreamReader和OutputStreamWriter将一个文本文件(使用的是utf-8的字符集),复制成一个使用gbk字符的的文本文件:
import java.io.*;
public class InputStreamReaderAndWriterTest {
public static void main(String[] args) {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
File file1 = new File("d:/io/hello_utf8.txt");
File file2 = new File("d:/io/hello_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
isr = new InputStreamReader(fis);
osw = new OutputStreamWriter(fos, "gbk");
char[] cbuf = new char[1024];
int len;
while ((len = isr.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
osw.write(cbuf[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (osw != null)
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
InputStreamReader是读入操作,所以要使用读入文本文件相对应的字符集。OutputStreamWriter是写入操作,所以第二参数是要使用的字符集去写入一个文本文件。