当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。