1 转换流
1.1 转换流出现的原因
- 由于字节流操作中文的时候不是很方便,所以,Java就提供了转换流。
- 字符流=字节流+编码表。
1.2 String类的编码和解码功能
- 方法:通过指定的编码,将二进制的数据转换为字符串,即解码
String(byte[] bytes, Charset charset)
- 方法:通过制定的编码,将字符串转换为二进制的数据,即编码
public byte[] getBytes(Charset charset)
package com.xuweiwei;
import java.io.UnsupportedEncodingException;
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "abcdef";
//编码
byte[] bytes = str.getBytes("UTF-8");
for (byte aByte : bytes) {
System.out.println("aByte = " + aByte +"、" );
}
//解码
System.out.println("解码:"+new String(bytes,"UTF-8"));
}
}
2 OutputStreamWriter
public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException
package com.xuweiwei;
import java.io.*;
public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {
Writer ow = new OutputStreamWriter(new FileOutputStream("ow.txt"),"utf-8");
ow.write("你好,许威威");
ow.close();
}
}
3 InputStreamReader
public InputStreamReader(InputStream in, String charsetName) throws UnsupportedEncodingException
package com.xuweiwei;
import java.io.*;
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
Reader reader = new InputStreamReader(new FileInputStream("ow.txt"),"utf-8");
char[] buffer = new char[1024];
int len = 0;
while(-1 != (len = reader.read(buffer))){
System.out.println(new String(buffer,0,len));
}
reader.close();
}
}
4 转换流的简化写法
- 抓换流的名字比较长,而我们常见的操作都是按照本地默认编码实现的,所以, 为了简化我们的书写,转换流就提供了对应的子类。
- 例如:FileWriter和FileReader。
package com.xuweiwei;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("fw.txt");
fw.write("你好啊");
fw.close();
}
}
5 字符缓冲流
public void newLine() throws IOException
package com.xuweiwei;
import java.io.*;
public class BufferedWriterDemo {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
bw.write("你好啊");
bw.flush();
bw.close();
}
}
package com.xuweiwei;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("fw.txt");
fw.write("你好啊");
fw.close();
}
}
package com.xuweiwei;
import java.io.*;
public class CopyDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
String line = null;
while(null != (line = br.readLine())){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
}