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();

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM