字符流带有缓冲区而 字节流没有缓冲区
当我们要复制音频,图片时考虑字节流(InputStream/OutputStream),文本时叫考虑字符流(Reader/Writer)
这是字节流复制图片的代码
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 public class FileCopy { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) { 13 FileInputStream fis=null; 14 FileOutputStream fos=null; 15 try { 16 fis=new FileInputStream("D:/3_31.png"); 17 fos=new FileOutputStream("F:/3_312.png"); 18 byte [] buffer=new byte[1024]; 19 int date; 20 while((date=fis.read(buffer))!=-1){ 21 //fis.read(buffer); 22 fos.write(buffer); 23 fos.flush(); 24 } 25 /* 26 * 或是 27 * int date; 28 * while((date=fis.read())!=-1){ 29 * fos.write(date); 30 * fos.flush(); 31 *} 32 */ 33 System.out.println("复制成功"); 34 35 } catch (FileNotFoundException e) { 36 e.printStackTrace(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 finally{ 41 try { 42 fos.close(); 43 fis.close(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 } 49 50 }
字符流复制文档
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.Reader; 8 import java.io.Writer; 9 10 public class FileReaderTest { 11 12 /** 13 * @param args 14 */ 15 public static void main(String[] args) { 16 Reader fr=null; 17 StringBuffer sb=null; 18 BufferedReader br=null; 19 Writer fw=null; 20 BufferedWriter bw=null; 21 22 try { 23 fr=new FileReader("F:/Myhi.txt"); 24 br=new BufferedReader(fr); 25 fw=new FileWriter("G:/book.txt"); 26 bw=new BufferedWriter(fw); 27 String str; 28 while((str=br.readLine())!=null){ 29 //System.out.println(str); 30 bw.write(str); 31 bw.newLine(); 32 bw.flush(); 33 } 34 System.out.println("写入成功"); 35 } catch (FileNotFoundException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } catch (IOException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } 42 finally{ 43 try { 44 bw.close(); 45 fw.close(); 46 br.close(); 47 fr.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 } 53 }
这只是最基本的使用的.
时间: 2024-10-24 09:54:48