//传入参数都需要 字节流
package 练习;
import org.junit.Test;
import java.io.*;
/*
inputstreamreader 字节流 ---》字符流
outputstreamwriter 字符流----》字节流 原理
是一套操作
其中他们的参数都需要字节流
*/
public class InputStreamOutputStreamReader {
// 字节流转换成字符流--------解码
@Test
public void testInputStreamReader() {
FileInputStream fi = null;
InputStreamReader isr = null;
try {
File file = new File("F:\\java92\\src\\练习\\1.txt");
fi = new FileInputStream(file);
// 字节流转换成字符流--------解码
//第二个参数表示读取文件的编码方式
isr = new InputStreamReader(fi, "gbk");
char[] ch = new char[20];
int len;
while ((len = isr.read(ch)) != -1) {
for (int i = 0; i < len; i++) {
System.out.print(ch[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fi != null) {
fi.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testOutStreamWrite() {
FileInputStream fi = null;
FileOutputStream fis = null;
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
File file = new File("F:\\java92\\src\\练习\\1.txt");
File file2 = new File("F:\\java92\\src\\练习\\2.txt");
fi = new FileInputStream(file);
fis = new FileOutputStream(file2);
// 字符流转换成字节流--------编码
//第二个参数表示读取文件的编码方式
isr = new InputStreamReader(fi, "gbk");
osw = new OutputStreamWriter(fis, "utf8");
char[] ch = new char[20];
int len;
while ((len = isr.read(ch)) != -1) {
for (int i = 0; i < len; i++) {
osw.write(ch[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (osw != null) {
osw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fi != null) {
fi.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转换流 inputstreamreader outputstreamwriter
最新推荐文章于 2022-04-22 06:00:00 发布