Java.io.InputStream.mark() 方法



描述

java.io.InputStream.mark(int readlimit) 方法標記此輸入流中的當前位置。隨後呼叫 reset() 方法會將流重新定位到最近標記的位置。

宣告

以下是java.io.InputStream.mark(int readlimit) 方法的宣告:

public void mark(int readlimit)

引數

readlimit − 在標記位置失效之前可以讀取的位元組最大數量。

返回值

此方法不返回值。

異常

示例

以下示例演示了 java.io.InputStream.mark(int readlimit) 方法的用法。

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null;
            
      try {
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         // read and print characters one by one
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
                     
         // mark is set on the input stream
         is.mark(0);
         
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
         
         if(is.markSupported()) {
         
            // reset invoked if mark() is supported
            is.reset();
            System.out.println("Char : "+(char)is.read());
            System.out.println("Char : "+(char)is.read());
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

假設我們有一個文字檔案c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入:

ABCDEF

讓我們編譯並執行上述程式,這將產生以下結果:

Char : A
Char : B
Char : C
Char : D
Char : E
java_io_inputstream.htm
廣告