文件字节流
FileInputStream:字节方式读取文件(适合读取所有类型文件)
FileOutputStream:字节方式输出到文件中
IO基本步骤:
1、创建源
2、选择流
3、操作
4、关闭流
FileInputStream
//创建源File src = new File("Garden.txt");//选择流InputStream is = null;//操作try {
is = new FileInputStream(src);byte[] flush = new byte[1024];int len; //实际长度//read(byte[]);返回读到的数据的长度//read();返回char,一个一个读//此处为纯文本,将其打印出来while((len = is.read(flush))!=-1){
String temp = new String(flush,0,len);System.out.println(temp);}} catch (FileNotFoundException e) {
e.printStackTrace();} catch (IOException e) {
e.printStackTrace();}finally {
//关闭流//null的判断不要忘try {
if (null!=is) {
is.close();}} catch (IOException e) {
e.printStackTrace();}}
FileOutputStream
File dest = new File("dest02.txt");OutputStream os = null;try {
os = new FileOutputStream(dest,true);//操作的是字节,需要将内容转化为字节数组String str = "Upsy Daisy";byte[] flush = str.getBytes();os.write(flush,0,str.length());os.flush(); //记得flush} catch (FileNotFoundException e) {
e.printStackTrace();} catch (IOException e) {
e.printStackTrace();}finally {
try {
if (null!=os) {
os.close();}} catch (IOException e) {
e.printStackTrace();}}
利用文件字节流拷贝文件
注意先开的流后关闭,且要分别关闭。
File src = new File("Garden.txt");File dest = new File("GardenCopy.txt");InputStream is = null;OutputStream os = null;try {
is = new FileInputStream(src);os = new FileOutputStream(dest);byte[] flush = new byte[1024];int len;//读、写while ((len = is.read(flush))!=-1){
os.write(flush,0,len);os.flush();}} catch (FileNotFoundException e) {
e.printStackTrace();} catch (IOException e) {
e.printStackTrace();}finally {
try {
if (null!=os) {
os.close();}} catch (IOException e) {
e.printStackTrace();}try {
if (null!=is) {
is.close();}} catch (IOException e) {
e.printStackTrace();}}