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


Java Java.io.LineNumberReader.read()用法及代碼示例


描述

這個java.io.LineNumberReader.read(char[] cbuf, int off, int len)方法將字符讀入數組的一部分。

聲明

以下是聲明java.io.LineNumberReader.read(char[] cbuf, int off, int len)方法 -

public int read(char[] cbuf, int off, int len)

參數

  • cbuf− 目標字符緩衝區。

  • off- 開始存儲字符的偏移量。

  • len− 要讀取的最大字符數。

返回值

該方法返回讀取的字節數,如果已到達流的末尾,則返回 -1。

異常

IOException− 如果發生 I/O 錯誤。

示例

下麵的例子展示了 java.io.LineNumberReader.read(char[] cbuf, int off, int len) 方法的用法。

package com.tutorialspoint;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberReaderDemo {
   public static void main(String[] args) throws IOException {
      FileReader fr = null;
      LineNumberReader lnr = null;
      int i;
      char[] cbuf = new char[5];
      
      try {
         // create new reader
         fr = new FileReader("C:/test.txt");
         lnr = new LineNumberReader(fr);
         
         // read characters into the buffer
         i = lnr.read(cbuf, 2, 3);
         System.out.println("Number of char read:"+i);
         
         // for each character in the buffer
         for(char c:cbuf) {
         
            // if char is empty
            if((int)c == 0)
               c = '-';
            
            // prints char
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      } finally {
         // closes the stream and releases system resources
         if(fr!=null)
            fr.close();
         if(lnr!=null)
            lnr.close();
      }
   }
}

假設我們有一個文本文件c:/test.txt,其內容如下。該文件將用作我們示例程序的輸入 -

ABCDE

讓我們編譯並運行上麵的程序,這將產生以下結果 -

Number of char read:3
--ABC

相關用法


注:本文由純淨天空篩選整理自 Java.io.LineNumberReader.read() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。