字节流
1 package com.lovo.test; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.OutputStream; 9 10 public class TestByteStream { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 //1、字节流 15 //声明流 16 InputStream in = null; 17 OutputStream out = null; 18 try { 19 //创建流 20 in = new FileInputStream("D:" + System.getProperty("file.separator") + "lileihanmeimei.mp3"); 21 out = new FileOutputStream("E:" + System.getProperty("file.separator") + "j124.mp3"); 22 23 //操作流 24 // int b = 0; 25 // while((b = in.read()) != -1){ 26 // out.write(b); 27 // } 28 29 byte[] b = new byte[1024]; 30 int length = 0; 31 while((length = in.read(b)) != -1){ 32 out.write(b,0,length); 33 out.flush();//冲刷 34 } 35 36 37 } catch (FileNotFoundException e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 } catch (IOException e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } finally{ 44 //关闭流 45 if(in != null){ 46 try { 47 in.close(); 48 } catch (IOException e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 } 52 } 53 if(out != null){ 54 try { 55 out.close(); 56 } catch (IOException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 } 61 } 62 63 } 64 65 }
字符流:步骤和上面一样
1 package com.lovo.test; 2 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 import javax.swing.JOptionPane; 11 12 public class TestCharStream { 13 14 public static void main(String[] args) { 15 // TODO Auto-generated method stub 16 17 // String msg = JOptionPane.showInputDialog("请输入‘白日依山尽’的下一句:"); 18 // 19 // Writer w = null; 20 // 21 // try { 22 // w = new FileWriter("poem.txt"); 23 // char[] b = msg.toCharArray(); 24 // w.write(b); 25 // w.flush(); 26 // } catch (IOException e) { 27 // // TODO Auto-generated catch block 28 // e.printStackTrace(); 29 // } finally{ 30 // if(w != null){ 31 // try { 32 // w.close(); 33 // } catch (IOException e) { 34 // // TODO Auto-generated catch block 35 // e.printStackTrace(); 36 // } 37 // } 38 // } 39 40 41 Reader r = null; 42 try { 43 String result = ""; 44 r = new FileReader("poem.txt"); 45 char[] c = new char[10]; 46 int length = 0; 47 while((length = r.read(c)) != -1){ 48 String str = new String(c, 0, length); 49 result += str; 50 } 51 System.out.println(result); 52 53 } catch (FileNotFoundException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } catch (IOException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 }finally{ 60 if(r != null){ 61 try { 62 r.close(); 63 } catch (IOException e) { 64 // TODO Auto-generated catch block 65 e.printStackTrace(); 66 } 67 } 68 } 69 } 70 }
时间: 2024-11-05 19:28:08