您的位置:首页 > Web前端

String BuffferedReader和sacnner

2015-06-14 15:42 375 查看

JAVA键盘输入:Scanner和BufferedReader

public class ScannerTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//sc.useDelimiter("\n");
while(sc.hasNext())
{
System.out.println("content "+sc.next());
}
}
}

System表示当前java程序的运行平台,无法创建System类的对象,只能调用System类的类方法和类属性.

System类提供了访问系统属性和环境变量的方法

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class SystemTest {
public static void main(String[] args) throws IOException {
Map<String,String>env=System.getenv();
for(String key:env.keySet())
{
System.out.println(key+">>"+env.get(key));
}
System.out.println("===============");
//		打印指定环境变量
System.out.println(env.get("JAVA_HOME"));
Properties props=System.getProperties();
//			  系统属性被保存在指定的txt中
props.store(new FileOutputStream("props.txt"), "System properties");
}

}

Scanner类用来接收键盘输入

sc.useDelimiter("\n");表示采用回车键作为分隔符.如果没有这段代码,输入

learn java

运行结果是:

content learn

content java

如果有这行代码,忽略空格,只把回车做分隔符,运行结果为:

content learn java

useDelimiter(String pattern)该方法参数应该为正则表达式

除了把回车作为分隔符之外,还可以使用hasNextLine()方法来返回下一行,可以将上面的程序改写为

public class ScannerTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//sc.useDelimiter("\n");
while(sc.hasNext())
{
System.out.println("content "+sc.next());
}
}
}

Scanner还可以被用来读取txt文件

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

public class ScannerTest2 {
public static void main(String[] args) throws FileNotFoundException {
//		使用Scanner来读取文件输入
//		如果a文件不存在:
//		Exception in thread "main"
//		java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
Scanner sc=new Scanner(new File("../a.txt"));
System.out.println("contents of a.txt");
while(sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
}

}

BufferedReader是在1.5之前用来读取键盘输入的,它需要建立在字符流的基础之上,所以需要用InputStreamReader来包装System.in

BufferedReader bf=new BufferedReader(new InputStreamReader(System.in);

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

public class BufferedReaderTest {
public static void main(String[] args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String sbr="";
while((sbr= bf.readLine())!=null)
{
System.out.println(sbr);
}
}

}

除了String类型,Scanner还能读取int.下面的代码将输入的数字逐行相加,并且打印.BufferedReader只能读取String

public class ScannerTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//	sc.useDelimiter("\n");
int i=0;
while(sc.hasNext())
{
//	    System.out.println("content "+sc.next());
i+=sc.nextInt();
System.out.println(i);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: