朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不尽,轻舟已过万重山。
——早发白帝城
我们老师写代码有个特点,就是简洁。每一句的意图都十分明确。所以他讲课的速度也比较快。
跑题了,说说I/O流:
1、字节输入流
2、字符输入流
3、字节输出流
4、字符输出流
上代码:
1 public class FileInputStreamAndFileoutputSteamDemo { 2 3 public static void main(String[] args) throws IOException { 4 FileOutputStream fos = new FileOutputStream("/home/yanshaochen/public/abc.txt"); 5 byte[] bytes = new byte[1024]; 6 bytes = "金麟岂是池中物,一遇风云变化龙".getBytes(); 7 fos.write(bytes); 8 fos.close(); 9 FileInputStream fis = new FileInputStream("/home/yanshaochen/public/abc.txt"); 10 String str = ""; 11 int data; 12 while ((data = fis.read(bytes)) != -1) { 13 str += new String(bytes, 0, data); 14 } 15 System.out.println(str); 16 fis.close(); 17 } 18 }
1 public class WriterAndReader { 2 3 public static void main(String[] args) throws IOException { 4 String path = "/home/yanshaochen/public/abc.txt"; 5 Writer wt = new FileWriter(path); 6 String str = "AAAAA"; 7 wt.write(str); 8 wt.close(); 9 Reader rd = new FileReader(path); 10 char[] chars = new char[16]; 11 int data; 12 str = ""; 13 while ((data = rd.read(chars))!=-1) { 14 str += new String(chars, 0, data); 15 } 16 System.out.println(str); 17 rd.close(); 18 } 19 }
带缓冲区的字符输入输出流
1 public class BufferedReaderAndBufferedWriter { 2 3 public static void main(String[] args) throws IOException { 4 Writer fw = new FileWriter("/home/yanshaochen/public/abc.txt"); 5 BufferedWriter bw = new BufferedWriter(fw); 6 String str = "AAAAAAAA"; 7 bw.write(str); 8 bw.newLine(); 9 bw.close(); 10 Reader fr =new FileReader("/home/yanshaochen/public/abc.txt"); 11 BufferedReader br = new BufferedReader(fr); 12 while ((str = br.readLine())!= null) { 13 System.out.println(str); 14 } 15 br.close(); 16 } 17 }
字节流读写二进制
1 public class DataInputStreamDemo { 2 3 public static void main(String[] args) throws IOException { 4 //原始地址 5 InputStream is = new FileInputStream("/home/yanshaochen/图片/2017-05-06 15-12-02屏幕截图.png"); 6 DataInputStream dis = new DataInputStream(is); 7 //目标地址 8 OutputStream os = new FileOutputStream("/home/yanshaochen/public/2017-05-06 15-12-02屏幕截图.png"); 9 DataOutputStream dos = new DataOutputStream(os); 10 byte[] bytes = new byte[1024]; 11 int data; 12 while((data = dis.read(bytes)) != -1){ 13 dos.write(bytes,0,data); 14 } 15 System.out.println("copy ok!"); 16 dos.close(); 17 dis.close(); 18 } 19 }