2016-01-22 113 views
1

這裏是我的文件C://test.txt組成 ACBDE FGHIJ如何讀取InputStream中間的偏移量?

我想讀它是F開始一路J. 所以輸出FGHIJ的。我將如何在InputStream中使用偏移量進行讀取。 這是我的部分實現。

InputStream is = null; 
byte[] buffer = null; 
char c; 

try { 
    is = new FileInputStream("D://test.txt"); 
    buffer = new byte[is.available()]; 
    System.out.println("Characters printed:"); 
    is.read(buffer, 5, 5); 
    for (byte b : buffer) { 

     if (b == 0) 
      // if b is empty 
      c = '-'; 
     else 
      c = (char) b; 

     System.out.print(c); 
     } 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    if (is != null) 
     is.close(); 
} 

請幫我萬阿英,蔣達清:d

回答

0

here,第二個參數是「開始的目標數組中的偏移」沒有文件偏移量,我想你錯了這一點,所以你可以嘗試閱讀這一切,然後找到第一個空格字符然後開始打印,這樣的:

InputStream is = null; 
    byte[] buffer = null; 
    char c; 
    boolean canPrint = false; 

    try { 
     is = new FileInputStream("/Users/smy/test.txt"); 
     buffer = new byte[is.available()]; 
     System.out.println("Characters printed:"+is.available()); 
     is.read(buffer, 0, is.available()); 
     for (byte b : buffer) { 

      if ((char)b == ' ') 
       // if b is empty 
       canPrint = true; 
      else{ 
       c = (char) b; 

       if (canPrint){ 
        System.out.print(c); 
       }} 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (is != null) 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
    } 

或者您可以使用RandomAccessFile來設定偏移的文件,然後開始閱讀。

+0

實際上,要求是使用輸入流的源。然後遍歷它或在字節中間的某個地方讀取它。 – teodoro

+0

如果您無法訪問具有偏移量的流,則可以像我的代碼所示一樣讀取它。 – starkshang

1

如果你想在第n個字符,你可以做到這一點,開始:

public static void file_foreach_offset(String file, int offset, IntConsumer c) throws IOException { 

     try(Stream<String> stream = Files.lines(Paths.get(file))) { 
      stream.flatMapToInt(String::chars) 
        .skip(offset) 
        .forEach(c); 
     } 
    } 
+0

是否有使用輸入流?我正在使用java 1.7 – teodoro

1

read()offset參數偏移到緩衝區,而不是文件。你要找的是seek()方法,後面跟着一個read(),偏移量爲零。

注意這是available()的經典誤用。看到Javadoc。有一個特定的警告,將其用作輸入流的長度。