IO流,字节流
程序员文章站
2022-03-17 09:49:43
2 /** 3 * IO流,字节流 4 */ 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 8 public class ByStreamDemo { 9 public static void main(... ......
2 /** 3 * IO流,字节流 4 */ 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 8 public class ByStreamDemo { 9 public static void main(String[] args) throws Exception{ 10 // demo_write(); 11 // demo_read_1(); 12 demmo_read_2(); 13 } 14 //写入数据 15 public static void demo_write() throws Exception{ 16 //获取文件 17 FileOutputStream fos = new FileOutputStream("F:\\1.txt"); 18 //写入数据"abcdefg" 19 fos.write("abcdefg".getBytes()); 20 //关闭流 21 fos.close(); 22 } 23 //读取数据1 24 public static void demo_read_1() throws Exception{ 25 //获取文件 26 FileInputStream fis = new FileInputStream("F:\\1.txt"); 27 //声明一个数据类型 28 int ch = 0; 29 //遍历输出 30 while((ch = fis.read()) != -1) { 31 System.out.print((char) ch); 32 } 33 } 34 //获取数据2 35 public static void demmo_read_2() throws Exception{ 36 //获取文件 37 FileInputStream fis = new FileInputStream("F:\\1.txt"); 38 //声明一个数组 39 byte buf[] = new byte[1024]; 40 //声明一个数据类型 41 int len = 0; 42 //遍历输出 43 while((len = fis.read(buf)) != -1) { 44 System.out.println(new String(buf, 0, len)); 45 } 46 } 47 }