1 import java.io.BufferedInputStream; 2 import java.io.BufferedOutputStream; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 /** 9 * 测试文件的读取、写入、复制功能 10 * @package :java05 11 * @author shaobn 12 * @Describe :测试文件的读取、写入、复制功能 13 * @Time: 2015-9-5 下午10:50:18 14 */ 15 public class TestCopyText { 16 public static void main(String[] args) throws Exception{ 17 //读取文件并打印 18 System.out.println(readText(new FileInputStream("D:\\hello.txt"))); 19 //写入内容至文件 20 writeText(new FileOutputStream("D:\\hellocopy.txt"), "您好,读写文件一般都用字符流,这种方式不推荐!"); 21 //复制文件,上面写入文件内容不变 22 writeText(new FileOutputStream("D:\\hellocopy.txt",true),readText(new FileInputStream("D:\\hello.txt"))); 23 } 24 //用FileInputStream读取文件 25 public static String readText(InputStream is){ 26 BufferedInputStream bis = null; 27 String str = null; 28 try { 29 bis = new BufferedInputStream(is); 30 int len = 0; 31 byte[] by = new byte[1024]; 32 while((len=bis.read(by))!=-1){ 33 str = new String(by,0,len); 34 } 35 } catch (Exception e) { 36 // TODO: handle exception 37 e.printStackTrace(); 38 }finally{ 39 try { 40 if(bis!=null){ 41 bis.close(); 42 return str; 43 } 44 } catch (Exception e2) { 45 // TODO: handle exception 46 e2.printStackTrace(); 47 } 48 } 49 return str; 50 } 51 //用FileOutputStream写入文件 52 public static void writeText(OutputStream os,String str){ 53 BufferedOutputStream bos = null; 54 try { 55 bos = new BufferedOutputStream(os); 56 bos.write(str.getBytes()); 57 } catch (Exception e) { 58 // TODO: handle exception 59 e.printStackTrace(); 60 }finally{ 61 try{ 62 if(bos!=null){ 63 bos.close(); 64 } 65 }catch (Exception e) { 66 // TODO: handle exception 67 e.printStackTrace(); 68 } 69 70 } 71 72 } 73 }
声明一下:一般读写文本文件均为字符流,笔者用字节流来写,推荐大家使用字符流读写文本文件。
时间: 2024-10-24 03:15:28