首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java中的IO流学问总结

2013-11-09 
Java中的IO流知识总结/*** Description: Test the java IO’s efficiency* Author: AllanCao* Date: 2007-0

Java中的IO流知识总结

/*** Description: Test the java IO’s efficiency* Author: AllanCao* Date: 2007-02-18*/import java.io.*;/*** using the InputStreamReader And OutputStreamWriter*/class EncoderRW { public static String read(String fileName) throws IOException { StringBuffer sb = new StringBuffer(); /*此处读文件时用了buffer,如果不用,性能损失一倍*/ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), “utf-8″)); String s; while((s = in.readLine()) != null) { sb.append(s); sb.append(”\n”); } in.close(); return sb.toString(); } public void write(String fileName, String text) throws IOException { OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),”utf-8″); out.write(text); out.flush(); out.close(); }}/*** using the BufferedReader And BufferedWriter*/class WriterReader { public String read(String fileName) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new FileReader(fileName)); String s; while((s = in.readLine()) != null) { sb.append(s); sb.append(”\n”); } in.close(); return sb.toString(); } public void write(String fileName, String text) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); out.print(text); out.close(); }}/*** using the BufferedInputStream And BufferedOutputStream*/class BufferedStream{ public byte[] read(String fileName) throws IOException { BufferedInputStream remoteBIS = new BufferedInputStream(new FileInputStream(fileName)); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while(bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } byte[] content = baos.toByteArray(); return content; } public void write(String fileName, byte[] content) throws IOException { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName)); out.write(content); out.flush(); out.close(); }}public class TestIO{ public static void main(String[] args)throws IOException { long currentTime = System.currentTimeMillis() ; EncoderRW rw = new EncoderRW(); rw.write(”index.dat”,rw.read(”FileUtil.java”)); System.out.println(”cost time:” + Long.toString(System.currentTimeMillis()-currentTime) + ” ms”); currentTime = System.currentTimeMillis() ; WriterReader wr = new WriterReader(); wr.write(”index.dat”,wr.read(”FileUtil.java”)); System.out.println(”cost time:” + Long.toString(System.currentTimeMillis()-currentTime) + ” ms”); currentTime = System.currentTimeMillis() ; BufferedStream bf = new BufferedStream(); bf.write(”index.dat”,bf.read(”FileUtil.java”)); System.out.println(”cost time:” + Long.toString(System.currentTimeMillis()-currentTime) + ” ms”); }}?

?

1 楼 fengweiyou 2011-10-08   说实话,写的不错. 条例清晰,分析到位.代码范例也很合适

热点排行