您的位置:首页 > 编程语言 > Java开发

关于java.util.Scanner

2015-06-16 21:46 417 查看
这几天想用Java获取控制台输入,用到了Scanner,后来还用到了Scanner读取文件的功能,现在总结一下。

API:http://tool.oschina.net/apidocs/apidoc?api=jdk_6u30

java.util.Scanner是Java5的新特征,主要功能是简化文本扫描、获取控制台输入。

下面是一些使用示例:

一、获取控制台输入

import java.util.Scanner;

public class TestScanner {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Waiting input");
while (true) {
String temp = scn.nextLine();
if (temp.trim().equals("exit")) {
return;
}
System.out.println("Your input is: " + temp);
}
}
}


通过new Scanner(Sysem.in)创建一个Scanner,控制台会一直等待输入,直到敲回车结束,把所输入的内容传给Scanner,作为扫描对象。如果要获取输入的内容,则只需要调用Scanner的nextLine()(或者next())方法即可。

补充:nextLine()和next()方法的区别:

nextLine()运行结果:



改成next()之后,运行结果为:



区别显而易见:

scanner可以允许输入多行,

next() 每次取到一个间隔符前面的数据 如: 输入 Hello World 取值应该是Hello,因为Hello后面有空格

nextLine() 每次取一个换行符前面的数据 如:输入 Hello World 回车,取值 就是Hello World

nextInt() 是取next() 然后把字符串解析成一个int数字。(此外,还有nextLong()、nextShort()方法,可参见API)

hasNextInt() 是判断下次调用next()是否可以得到一个可以安全解析成int的字符串。如果已经到达输入的结尾,或者下一个next()的返回值不能解析为一个数字,即不符合数字的格式,那么返回false。

重要的一点如果不使用Scanner,用其他方法获取控制台输入比较痛苦。

1、使用System.in

public class UseSystemIn {
public static void main(String[] args) {
System.out.println("Waiting input");

byte[] b = new byte[1024];  // 数组缓冲
int n = 0;  // 有效数据个数
try {
while (true) {
// The number of bytes actually read is returned as an integer.
n = System.in.read(b); // Reads some number of bytes from the input stream and stores them into the buffer array b
String s = new String(b, 0, n-2);  // 转换为字符串
if (s.equalsIgnoreCase("exit")) {
break; // 结束循环
}
System.out.println("Your input is: " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上述代码中,加入了一个while循环,可以让用户输入多次。在用户输入时,送入输入流的内容除了用户输入的内容以外,还包含了“\r\n”这两个字符,所以在将输入的内容和eixt进行比较时,去掉读出的最后两个字符,将剩余的内容转换为字符串。

运行结果:



2、使用BufferedReader

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UseBufferedReader {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting input");
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println("Your input is: " + line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


这里注意,对BufferedReader对象的创建,上述代码运行结果如下,用Ctrl+z来结束输入。



二、读取文件内容

借助Scanner的构造函数。

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

public class ReadFileUseScanner {
public static void main(String[] args) {
Scanner scn = null;
try {
scn = new Scanner(new File("D:\\test\\input.txt"));
while (scn.hasNextLine()) {
System.out.println(scn.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


注意:Scanner有很多构造函数,这里还可以使用scn = new Scanner(new FileInputStream(new File("D:\\test\\input.txt"))); —— 使用Scanner(InputStream source)

三、Scanner默认使用空格作为分隔符来分隔文本,但允许指定新的分隔符

使用默认的空格符:

import java.util.Scanner;

public class UseDelimiterScanner {
public static void main(String[] args) {
Scanner scn = new Scanner(
"123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las");
//	scn.useDelimiter(" |,|\\.");
while (scn.hasNext()) {
System.out.println(scn.next());
}
}
}


此时的运行结果为:



将注释行去掉,使用空格或逗号或点号作为分隔符,输出结果如下:



该运行结果中的空行,与空格数、逗号和点号的数目有关系,一个逗号的时候没有空行,n个逗号或其他的时候,有n-1个空行。

其他查看API。

参考:http://lavasoft.blog.51cto.com/62575/182467/
http://www.cnblogs.com/ydpvictor/archive/2012/06/17/2552981.html http://www.cnblogs.com/springcsc/archive/2009/12/03/1616372.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: