Java-键盘输入

缓冲区读取由两个类组成:

  1. BufferedInputStream
  2. BufferedReader(可读取一行文字,中文也可以)
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in);

String str = buf.readLine();

Scanner

  1. 判断是否有数据:public Scanner(InputStream source)
  2. 模式匹配:hasNext(“…”)
  3. 取得数据:public 数据类型 nextXxx()
  4. 设置换行符:useDelimiter()
// 通过Scanner输入数据
Scanner scan = new Scanner(System.in);
scan.useDelimiter("/n");// 使用回车作为换行符
if(scan.hasNext()){
    String str = scan.next();
}

程序输出数据使用打印流,输入数据使用Scanner

package com.joeaaa.file;
/*
* 使用Scanner读取文件
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFileTest {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new FileInputStream("/Users/joe/IdeaProjects/java/demo1/src/com/joeaaa/1.txt"));
        scan.useDelimiter("\n");
        while (scan.hasNext()){
            System.out.println(scan.next());
        }
        scan.close();
    }
}