Java Scanner close() 方法



描述

java Scanner close() 方法關閉此掃描器。如果此掃描器尚未關閉,則如果其底層可讀物件也實現了 Closeable 介面,則將呼叫可讀物件的 close 方法。如果此掃描器已關閉,則呼叫此方法將沒有任何效果。

宣告

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

public void close()

引數

返回值

此方法不返回值。

異常

在字串上關閉 Scanner 的示例

以下示例演示瞭如何使用 Java Scanner close() 方法關閉掃描器。我們使用給定的字串建立了一個掃描器物件。然後我們使用 nextLine() 方法列印字串,然後使用 close() 方法關閉掃描器。

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());

      // close the scanner
      System.out.println("Closing Scanner...");
      scanner.close();
      System.out.println("Scanner Closed.");
   }
}

輸出

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

Hello World! 3 + 3.0 = 6
Closing Scanner...
Scanner Closed.

在使用者輸入上關閉 Scanner 的示例

以下示例演示瞭如何使用 Java Scanner close() 方法關閉掃描器。我們使用 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());

      // close the scanner
      System.out.println("Closing Scanner...");
      scanner.close();
      System.out.println("Scanner Closed.");
   }
}

輸出

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

Hello World
Hello World
Closing Scanner...
Scanner Closed.

在屬性檔案上關閉 Scanner 的示例

以下示例演示瞭如何使用 Java Scanner close() 方法關閉掃描器。我們使用檔案 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());

      // close the scanner
      System.out.println("Closing Scanner...");
      scanner.close();
      System.out.println("Scanner Closed.");
   }
}

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

Height=200
Width=15

輸出

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

Height=200
Closing Scanner...
Scanner Closed.
java_util_scanner.htm
廣告