io流操作之文本读写代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class TestFileInputOutputStream {

    File file1 = new File("hello.txt");

    public void testFileOutputStream(){


        FileOutputStream fos = null;
        try{

            fos = new FileOutputStream(file1);
            fos.write(new String("I love China,I love World!").getBytes()); 

        }catch(Exception e){

            e.printStackTrace();

        }finally{
            if(fos !=null){
                try{
                    fos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }

            }
        }
    }

    public void testFileInputStream(){

        FileInputStream fis = null;
        //Byte[] b = new Byte[20];

        try{

            fis = new FileInputStream(file1);

            /*
             * 读取方法一:
             *  int b = fis.read();
                while(b!=-1){           
                    System.out.print((char)b);
                    b = fis.read();
            }*/

            /*
             * 读取方法二:
             *  int b;
                while((b=fis.read()) != -1){
                    System.out.print((char)b);
            }*/

            /*
             * 读取方法三:
             *  byte[] b = new byte[5];
                int len;
                while((len = fis.read(b)) !=-1){
                    for(int i=0 ; i<len ;i++){
                        System.out.print((char)b[i]);
                    }
            }*/

            //读取方法四:
            byte[] b = new byte[5];
            int len;
            while((len = fis.read(b)) !=-1){
            //通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
            新 String 的长度是字符集的函数,因此可能不等于该子数组的长度。
                String str = new String(b,0,len);
                System.out.print(str);
                }

        }catch(Exception e){

            e.printStackTrace();
        }finally{
            if(fis != null){
                try{
                    fis.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args){

        TestFileInputOutputStream  tio = new TestFileInputOutputStream();
        //tio.testFileOutputStream();
        tio.testFileInputStream();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值