Java Scanner ioException() 方法



描述

java.Scanner ioException() 方法返回此 Scanner 的底層 Readable 最近丟擲的 IOException。如果不存在此類異常,則此方法返回 null。

宣告

以下是 java.util.Scanner.ioException() 方法的宣告

public IOException ioException()

引數

返回值

此方法返回此掃描程式的可讀物件最近丟擲的異常

異常

使用字串示例檢查 Scanner 中的 ioException

以下示例演示瞭如何使用 Java Scanner ioException() 方法來檢查此 Scanner 的底層 Readable 最近丟擲的 IOException。我們使用給定的字串建立了一個掃描程式物件。然後我們使用 nextLine() 方法列印字串,然後列印任何異常。使用 close() 方法關閉 Scanner。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // print the next line of the string
      System.out.println(scanner.nextLine());
      
      System.out.println(scanner.ioException());
      // close the scanner
      scanner.close();

   }
}

輸出

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

Hello World! 3 + 3.0 = 6
null

使用使用者輸入示例檢查 Scanner 中的 ioException

以下示例演示瞭如何使用 Java Scanner ioException() 方法來檢查此 Scanner 的底層 Readable 最近丟擲的 IOException。我們使用 System.in 類建立了一個掃描程式物件。然後我們使用 nextLine() 方法列印字串,然後列印任何異常。然後使用 close() 方法關閉掃描程式。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      // create a new scanner with the system input
      Scanner scanner = new Scanner(System.in);

      // print the next line of the string
      System.out.println(scanner.nextLine());

      System.out.println(scanner.ioException());
      // close the scanner
      scanner.close();
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:(我們在其中輸入 Hello World 並按 Enter 鍵。)

Hello World
Hello World
null

使用屬性檔案示例檢查 Scanner 中的 ioException

以下示例演示瞭如何使用 Java Scanner ioException() 方法來檢查此 Scanner 的底層 Readable 最近丟擲的 IOException。我們使用檔案 properties.txt 建立了一個掃描程式物件。然後我們使用 nextLine() 方法列印內容,然後列印任何異常。然後使用 close() 方法關閉掃描程式。

package com.tutorialspoint;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) throws FileNotFoundException {

      // create a new scanner with a file as input
      Scanner scanner = new Scanner(new File("properties.txt"));

      // print the next line of the string
      System.out.println(scanner.nextLine());

      System.out.println(scanner.ioException());
      // close the scanner
      scanner.close();
   }
}

假設我們在你的 CLASSPATH 中有一個名為 properties.txt 的檔案,其內容如下。此檔案將用作我們示例程式的輸入:

Height=200
Width=15

輸出

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

Height=200
null
java_util_scanner.htm
廣告

© . All rights reserved.