當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BufferedInputStream skip(long)用法及代碼示例


Java中BufferedInputStream類的skip(long)方法用於從緩衝的輸入流中跳過n個字節的數據。跳過的字節數被存儲並作為long類型返回。終止條件涉及以下兩個之一:

  • 讀入字節數組,直到覆蓋了n-bytes為止,或者
  • 溫輸入的結尾,流被滿足。

但是,如果傳遞一個負值,則不會發生跳過。

用法:



public long skip(long n)

參數:此方法接受long類型的n,n表示需要從輸入流中跳過的字節數。

返回值:此方法返回跳過為long類型的字節數。

異常:如果已通過調用close()方法關閉了此輸入流,或者該流不支持查找,或者發生了任何其他I /O錯誤,則此方法將引發IOException。

以下示例程序旨在說明IO包中BufferedInputStream類中的skip(long)方法:

程序1:假設存在文件“c:/demo.txt”。

// Java program to illustrate  
// BufferedInputStream skip(long) method  
import java.io.*;  
public class GFG {  
    public static void main(String[] args)  
    {  
     
        // Create input stream 'demo.txt'  
        // for reading containing text "GEEK" 
        FileInputStream inputStream =   
        new FileInputStream("c:/demo.txt");  
     
        // Convert inputStream to   
        // bufferedInputStream  
        BufferedInputStream buffInputStr   
              = new BufferedInputStream( 
                          inputStream);  
           
        // Read until a single  
        // byte is available 
        while(buffInputStr.available()>0) { 
           
            // Skip single byte from the stream 
            buffInputStr.skip(1); 
           
            // Read next available byte and  
            // convert to char 
            char c = (char) buffInputStr.read(); 
           
            // Print character 
            System.out.print(" " + c); 
         } 
    } 
}
輸出:
 E K

程序2:假設存在文件“c:/demo.txt”。

// Java program to illustrate  
// BufferedInputStream skip(long) method  
import java.io.*;  
public class GFG {  
    public static void main(String[] args)  
    {  
     
        // Create input stream 'demo.txt'  
        // for reading containing text "GEEKSFORGEEKS" 
        FileInputStream inputStream =   
        new FileInputStream("c:/demo.txt");  
     
        // convert inputStream to   
        // bufferedInputStream  
        BufferedInputStream buffInputStr 
            = new BufferedInputStream( 
                        inputStream);  
           
        // Read until a single  
        // byte is available 
        while(buffInputStr.available()>0) { 
           
            // Skip single byte from the stream 
            buffInputStr.skip(3); 
           
            // Read next available byte and  
            // convert to char 
            char c = (char) buffInputStr.read(); 
           
            // Print character 
            System.out.print(" " + c); 
         } 
    } 
}
輸出:
K R K

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#skip(long)




相關用法


注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 BufferedInputStream skip(long) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。