021.3 IO流——字节流-FileInputStream读取字节

内容:文件读取方法,读取方法例子,read(buf)方法中buf的取值,字节流缓冲区对象—提高读取速度///

文件读取方法:fis.read(),fis.read(buf),具体看例子

例子:文件读取——读取文件,显示出来

public class FileInputStreamDemo
{
    public static void main(String[] args)
    {
        //为了确保文件一定在读之前一定存在。将字符串路径封装成File对象
        File file = new File("F:"+File.separator+"eclipse_javaCode"+File.separator+"day22"
        +File.separator+"src"+File.separator+"demo"+File.separator+"GetMoney.java");
        if(!file.exists()){
            throw new RuntimeException("文件不存在!");
        }
        
        //创建文件字节读取流对象
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            //第一种读取方法,单个读取
//            int ch = 0;
//            while(ch!=-1){
//                ch = fis.read();
//                System.out.println(ch);  //读取文件第一种方法,成功返回acsii码,失败返回-1
//            }
            //第二个读取方法,批量读取
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = fis.read(buf)) != -1){
                System.out.println(new String(buf,0,len));
            }
        } catch (IOException e) {
        }
    }
}

#################################################################
一般不直接创建相应大小的字节缓冲区
缓冲区大小一般是字节的倍数,1024的倍数

public static void main(String[] args) throws IOException
{
    File file = new File("F:\\eclipse_javaCode\\day21\\src\\day21\\shangxin.txt");
    System.out.println(file.length());    //获取文件字节数
    FileInputStream fis = new FileInputStream(file);
    System.out.println(fis.available());     //获取与之关联文件的字节数
    
    byte[] buf = new byte[fis.available()];   //一般不会一下子创建相应大小的缓冲区,比如是高清电影就麻烦了。
    //一般创建是1024的倍数
    fis.read(buf);
    String s = new String(buf);
    System.out.println(s);
    
    fis.close();
}

字节流-复制文本

public static void main(String[] args) throws IOException
{
    FileOutputStream fos = new FileOutputStream("xxx_copy.txt");
    FileInputStream fis = new FileInputStream("FileInputStreamDemo.java");
    
    byte[] buf = new byte[1024];
    int len = 0;
    while((len = fis.read(buf))!= -1){
        fos.write(buf,0,len);
        fos.flush();
    }
    
    fis.close();
    fos.close();
}

字节流的缓冲区对象
#####字节流复制文本—使用缓冲区对象,提高效率

private static void copyByBuffer() throws IOException
{
    FileInputStream fis = new FileInputStream("aaaa.txt");
    BufferedInputStream bufis = new BufferedInputStream(fis);
    
    FileOutputStream fos = new FileOutputStream("aaaa_copy.txt");
    BufferedOutputStream bufos = new BufferedOutputStream(fos);
    
    byte[] buf = new byte[1024];
    
    int by = 0;
    while((by = bufis.read(buf))!=-1){
        bufos.write(buf,0,by);
        bufos.flush();
    }
    
    fos.close();
    fis.close();

}

猜你喜欢

转载自www.cnblogs.com/-nbloser/p/8946499.html