今天我们来学习流的最后一部分:转换流InputStreamReader和OutputStreamWriter,缓冲转换流:BufferedReader和BufferedWriter
这几个我们学一下构造方法就可以了。成员方法跟字符流的都一样。
一:什么是转换流?
可以将字节流转换成字符流
转换流是所有流中唯一能设置编码方式的流
二:InputStreamReader
1 :构造方法
(1):public InputStreamReader(InputStream in)
(2):public InputStreamReader(InputStream in,String charsetName)
具体使用参见文件复制粘贴
三:OutputStreamWriter
1 :构造方法
(1):public OutputStreamWriter(OutputStream out)
(2):public OutputStreamWriter(OutputStream out,String charsetName)
具体使用参见文件复制粘贴
四:文件复制粘贴
1 :一次复制一个字符,一次写入一个字符
java
public static void main(String[] args) {
try {
InputStreamReader inp = new InputStreamReader(new FileInputStream("aaa.txt"));
OutputStreamWriter outp = new OutputStreamWriter(new FileOutputStream("bbb.txt", true));
int len = 0;
while ((len = inp.read()) != -1) {
outp.write(len);
}
outp.flush();
System.out.println("复制成功!");
} catch (Exception e) {
System.out.println("出错了!");
}
}
2 :一次读取一个字符数组,一次写出一个字符数组的一部分
java
public static void main(String[] args) {
try {
InputStreamReader inp = new InputStreamReader(new FileInputStream("aaa.txt"));
OutputStreamWriter outp = new OutputStreamWriter(new FileOutputStream("ccc.txt", true));
char[] ch = new char[1024];
int len = 0;
while ((len = inp.read(ch)) != -1) {
outp.write(ch, 0, len);
}
outp.flush();
System.out.println("复制成功!");
} catch (Exception e) {
System.out.println("出错了!");
}
}
3 :缓冲转换流:一次读取一个字符,一次写出一个字符
java
public static void main(String[] args) {
try {
BufferedReader inp = new BufferedReader(new InputStreamReader(new FileInputStream("aaa.txt")));
BufferedWriter outp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ddd.txt", true)));
int len = 0;
while ((len = inp.read()) != -1) {
outp.write(len);
}
outp.flush();
System.out.println("复制成功!");
} catch (Exception e) {
System.out.println("出错了!");
}
}
4 :缓冲转换流:一次读取一个字符数组,一次写出一个字符数组的一部分
java
public static void main(String[] args) {
try {
BufferedReader inp = new BufferedReader(new InputStreamReader(new FileInputStream("aaa.txt")));
BufferedWriter outp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ccc.txt", true)));
char[] ch = new char[1024];
int len = 0;
while ((len = inp.read(ch)) != -1) {
outp.write(ch, 0, len);
}
outp.flush();
System.out.println("复制成功!");
} catch (Exception e) {
System.out.println("出错了!");
}
}
5 :一次读取一行,一次写出一行
java
public static void main(String[] args) {
try {
BufferedReader inp = new BufferedReader(new InputStreamReader(new FileInputStream("aaa.txt")));
BufferedWriter outp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ccc.txt", true)));
String line = null;
while ((line = inp.readLine()) != null) {
line += "\n";
outp.write(line);
}
outp.flush();
System.out.println("复制成功!");
} catch (Exception e) {
System.out.println("出错了!");
}
}
以上大概就是转换流的基本使用。
有好的建议,请在下方输入你的评论。