IO流的复习笔记

IO字节流和缓冲流

IO字节流的读取和写入

读取

 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         try (FileInputStream fis = new FileInputStream("java.txt")
 8         ) {
 9             byte[] bytes = new byte[40];
10             int temp;
11             while ((temp = fis.read(bytes)) != -1) {
12                 System.out.println(new String(bytes, 0, temp));
13             }
14         } catch (FileNotFoundException e) {
15             e.printStackTrace();
16         } catch (IOException e) {
17             e.printStackTrace();
18         }
19     }
20 }

写入

 1 import java.io.*;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         try (FileOutputStream fos = new FileOutputStream("file" + File.separator + "1024.txt", true) //写入时不清除原有数据
 6         ) {
 7             fos.write("Hello".getBytes());
 8             fos.write("\n".getBytes());  //换行
 9             fos.write("Wrold!".getBytes());
10             fos.flush(); //刷新
11         } catch (FileNotFoundException e) {
12             e.printStackTrace();
13         } catch (IOException e) {
14             e.printStackTrace();
15         }
16     }
17 }

IO字节流的文件拷贝

 1 import java.io.*;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         try (
 6                 FileOutputStream fos = new FileOutputStream("file" + File.separator + "new.txt");
 7                 FileInputStream fis = new FileInputStream("java.txt")
 8         ) {
 9             int temp;
10             byte[] bytes = new byte[50];
11             while ((temp = fis.read(bytes)) != -1) {
12                 fos.write(bytes);
13             }
14         } catch (FileNotFoundException e) {
15             e.printStackTrace();
16         } catch (IOException e) {
17             e.printStackTrace();
18         }
19     }
20 }

IO缓冲流的读取和写入

读取

猜你喜欢

转载自www.cnblogs.com/xiaowangtongxue/p/10716108.html