標籤:[] 流轉 ade 字元 import 流操作 pac 子類 put
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
public String readLine()
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(); }}
Java基礎二十