详解Scanner类的各个构造方法和使用规则
时间: 2023-12-10 22:04:15 浏览: 55
Scanner类是Java中用于读取输入的类之一。它可以从多种数据源中读取输入,如文件、字符串、标准输入等等。Scanner类有多个构造方法,用于实现不同的输入方式。
Scanner类的构造方法:
1. Scanner(File source):从文件中读取输入;
2. Scanner(InputStream source):从输入流中读取输入;
3. Scanner(String source):从字符串中读取输入;
4. Scanner(Readable source):从可读对象中读取输入;
5. Scanner(ReadableByteChannel source):从可读字节通道中读取输入;
6. Scanner(Path source):从文件路径中读取输入;
7. Scanner(File source, String charsetName):从指定编码的文件中读取输入;
8. Scanner(InputStream source, String charsetName):从指定编码的输入流中读取输入;
9. Scanner(ReadableByteChannel source, String charsetName):从指定编码的可读字节通道中读取输入;
10. Scanner(Path source, String charsetName):从指定编码的文件路径中读取输入。
其中,第一个参数source表示输入源,可以是文件、输入流、字符串等等。第二个参数charsetName表示编码格式,可以省略,默认为UTF-8编码。
使用Scanner类的步骤:
1. 创建Scanner对象,指定输入源和编码格式;
2. 使用nextXxx()或hasNextXxx()方法读取输入。
示例代码:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
try {
// 从文件中读取输入
Scanner scanner1 = new Scanner(new File("input.txt"), "UTF-8");
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
System.out.println(line);
}
scanner1.close();
// 从标准输入中读取输入
Scanner scanner2 = new Scanner(System.in);
System.out.println("请输入一个整数:");
int n = scanner2.nextInt();
System.out.println("您输入的整数是:" + n);
scanner2.close();
// 从字符串中读取输入
String input = "Hello World!";
Scanner scanner3 = new Scanner(input);
while (scanner3.hasNext()) {
String word = scanner3.next();
System.out.println(word);
}
scanner3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
注意:使用Scanner类读取输入时,需要记得关闭Scanner对象,否则会导致资源泄漏。可以使用try-with-resources语句来自动关闭Scanner对象。