字节流
1 范例: 2 public class ByteDemo { 3 public static void main(String[] args) { 4 OutputStream os = null; 5 InputStream is = null; 6 FileOutputStream os1 = null; 7 try { 8 //1.创建文本文件 9 os = new FileOutputStream("E:\\Java实训课总结\\2016.3.26\\我的青春谁做主.txt"); 10 String str = "我的青春我做主,燃烧吧,少年!"; 11 String str2 = "yimifkaskfdajiofjaeiomvm我是几的司法计算女"; 12 byte[] b = str.getBytes(); 13 byte[] b2 = str2.getBytes(); 14 os.write(b); 15 os.write(b2); 16 os.flush(); 17 18 //2.读取文本内容 19 is = new FileInputStream("E:\\Java实训课总结\\2016.3.26\\我的青春谁做主.txt"); 20 byte[] data = new byte[1024]; 21 int len = -1; 22 //★len = is.read(data,0,data.length)★ 或者 ★i = is.read(copyData)★ // os1.write(copyData,0,copyData.length); 23 while ((len = is.read(data,0,data.length)) != -1) { 24 System.out.println(new String(data)); 25 } 26 27 //3.文件内容复制到另一个文本文件中 28 os1 = new FileOutputStream("E:\\Java实训课总结\\2016.3.26\\我的青春谁做主copy.txt"); 29 byte[] copyData = new byte[1024]; 30 int i = -1; 31 /** 32 * 1.字符流,如何读出的中文不是乱码,★打印的是new String(data)/new String(copyData)★ 33 * 2.怎么读取中英文本。同上 34 */ 35 while(((i = is.read(copyData)) != -1)) { 36 os1.write(copyData,0,copyData.length); 37 System.out.println(new String(copyData)); 38 } 39 //显示文本内容 40 os1.flush(); 41 System.out.println("复制完成"); 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } finally { 45 try { 46 // os1.close(); 47 os.close(); 48 is.close(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 } 54 } 55 56 -------------------二进制文件读写--------------------- 57 DataInputStream 58 FileInputStream的子类 59 与其父类一起使用,读取二进制文件 60 61 DataOutputStream 62 FileOutputStream的子类 63 与其父类一起使用,写出二进制文件 64 范例: 65 public class DataStreamDemo { 66 public static void main(String[] args) { 67 DataInputStream dis = null; 68 DataOutputStream dos = null; 69 try { 70 //构建二进制数据的输入流 71 dis = new DataInputStream(new FileInputStream("D:\\Documents\\My Pictures\\DSCF7863 (1).jpg")); 72 //构建二进制数据的输出流 73 dos = new DataOutputStream(new FileOutputStream("E:\\Java实训课总结\\2016.3.26" + File.separator + "picture.jpg")); 74 //读写文件 75 int len; 76 while ((len = dis.read()) != -1) { 77 dos.write(len); 78 } 79 } catch (FileNotFoundException e) { 80 e.printStackTrace(); 81 } catch (IOException e) { 82 e.printStackTrace(); 83 } finally { 84 //关闭流 85 try { 86 dos.close(); 87 dis.close(); 88 } catch (IOException e) { 89 e.printStackTrace(); 90 } 91 } 92 } 93 }