IO流 - 字节流
1.字节输出流
// 1.明确目的地 // 如果该文件不存在,就会创建一个 // 如果该文件存在,就会被覆盖 FileOutputStream fos = new FileOutputStream("D:\\java1018\\f.txt");//未开启续写功能 FileOutputStream fos = new FileOutputStream("D:\\java1018\\f.txt",true);//开启续写功能 //2.写入字节 //单字节 fos.write(100);//根据ASCII码值 //字节数组 byte [] bytes={-66,-67,-68,-69};//正数走ASCII码值,负数走中文码表,一个汉字两个字节 fos.write(bytes);//写入全部 fos.write(bytes, 0, 4);//从第零个开始,向后写4个长度 fos.write("新年好".getBytes());//string 字节转换 fos.write("\r\nhello".getBytes());// \r\n 换行 //释放资源 fos.close();
2.字节输出流异常处理
FileOutputStream fos = null; try { fos = new FileOutputStream("D:\\java1018\\f.txt", true); fos.write("新年好".getBytes()); fos.write("\r\nhello".getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
3.字节输入流
//1.明确目的地 FileInputStream fis = new FileInputStream("D:\\java1018\\f.txt"); //2.读取文件 int read = 0; while ((read=fis.read())!=-1) { System.out.print((char) read);//char强转 } //3.释放资源 fis.close();
4.用字节数组读取文件
//1.明确目的地 FileInputStream fis = new FileInputStream("D:\\java1018\\f.txt"); //2.创建字节数组 byte [] bytes=new byte[1024]; //3.读取文件 int len=0;//实际读了几个值(有效长度) while ((len=fis.read(bytes))!=-1) { System.out.print(new String(bytes,0,len));//判断读多少,读有效长度 } //4.释放资源 fis.close();

浙公网安备 33010602011771号