三、控制台输入Scanner

1、Scanner用来接收控制台的输入

(1)想通过控制台进行输入,首先需要构造一个 Scanner 对象,并与“ 标准输人流” System.in 关联。

Scanner in = new Scanner(System.in);

(2)要想对文件进行读取,就需要一个用 File 对象构造一个 Scanner 对象,如下所示:

Scanner in = new Scanner(Paths.get("myflle.txt"), "UTF-8");

如果文件名中包含反斜杠符号,就要记住在每个反斜杠之前再加一个额外的反斜杠:

“c:\my\myfile.txt ” ——>“c:\\my\\myfile.txt ”

(3)要想写入文件, 就需要构造一个 PrintWriter 对象。在构造器中,只需要提供文件名:

PrintWriter out = new PrintlulriterC'myfile.txt", "UTF-8");

2、Scanner测试

import org.junit.Test;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Scanner;
/**
/**
 * @ClassName Scanner
 * @Description 测试scanner类
 * @Author 洛城天使
 * @Date: 2021/9/18 22:50
 * @Version 1.0
 */
public class ScannerDemo {

    @Test
    public void testScanner() throws IOException {
        String filePath = "E:\\demofile\\javatest.txt";
        PrintWriter writer = new PrintWriter(filePath, "UTF-8");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一些字:");
        boolean falg = true;
        while (falg) {
            String str = scanner.nextLine();
            if ("exit".equals(str)) {
                System.out.println("====================");
                falg = false;
                writer.close();
            } else {
                writer.println(str);
                writer.flush();
            }
        }

        Scanner in = new Scanner(Paths.get(filePath), "UTF-8");
        while (in.hasNextLine()) {
            String line = in.nextLine();
            System.out.println(line);
        }

    }
}

你可能感兴趣的:(三、控制台输入Scanner)