首先不能迷:
字节流:OutputStream --> FileOutputStream,InputStream --> FileInputStream
字符流:Writer --> FileWriter,Reader --> FileReader
字符字节转换流:Writer --> OutputStreamWriter,Reader --> InputStreamReader
流向不同,相互转换:
* OutputStreamWriter:可以将输出的字符流转换为字节流的输出形式 * InputStreamReader:可以将输入的字节流转换为字符流的输入形式
示例:
import java.io.*; import java.nio.charset.Charset; public class demo_io3 { public static void main(String[] args) throws FileNotFoundException { // InputStream in = new FileInputStream("1.txt"); // read(in); OutputStream out = new FileOutputStream("1.txt",true); write(out); } //将输入流作为参数 public static void read(InputStream in){ //假如传进来的是一个文本,那么使用字符流会更好 //将字节的输入流转换为字符的输入流 Reader reader = new InputStreamReader(in, Charset.forName("UTF-8")); //处理字符 char[] chars = new char[1024]; int len = -1; try { while (((len=reader.read(chars))!=-1)) { System.out.println(new String(chars,0,len)); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } //将输出流作为参数 public static void write(OutputStream out){ Writer writer = new OutputStreamWriter(out,Charset.forName("UTF-8")); try { writer.write("哈哈哈哈哈"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)