看到几个方法:
这个似乎读入参数,eclipse中要在arguments中给出:
public static void main(String[] args) {
System.out.println("please type in an integer: ");
int i=Integer.parseInt(args[0]);
}
------------------------------------------------
这个比较好,读一串字符流
int n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
n = Integer.parseInt(str);
------------------------------------------
这个读一个字符
public static char readChar()
{
int charAsInt=-1;//to keep the compiler happy
try
{
charAsInt=System.in.read();
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.out.println("Fatal error.Ending program.");
System.exit(0);
}
return (char)charAsInt;
}
---------------------------------------------
这个似乎限制了读入的容量,没测试不确定
byte[] buffer=new byte[512];
System.in.read(buffer);
String str=new String(buffer);
---------------------
这个是读入密码,并且不回显,java从1.6版本开始,增加了一个java.io.Console类, 提供了像readPassword()等这样的实用方法,但是要注意的是:如果你在Eclipse里面启动程序调用Console,那么通常是没有控制台,还是得从外部的命令行方式才能调用得到。虚拟机是否具有控制台取决于底层平台,还取决于调用虚拟机的方式。如果虚拟机从一个交互式命令行开始启动,且没有重定向标准输入和输出流,那么其控制台将存在,并且通常连接到键盘并从虚拟机启动的地方显示。如果虚拟机是自动启动的(例如,由后台作业调度程序启动),那么它通常没有控制台。
也就是说用下面这个方法从eclipse中运行程序则不能用,console会为null
代码是官网上的:
http://download.oracle.com/javase/tutorial/essential/io/cl.html
import java.io.Console;
import java.util.Arrays;
import java.io.IOException;
public class Password {
public static void main (String args[]) throws IOException {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String login = c.readLine("Enter your login: ");
char [] oldPassword = c.readPassword("Enter your old password: ");
if (verify(login, oldPassword)) {
boolean noMatch;
do {
char [] newPassword1 =
c.readPassword("Enter your new password: ");
char [] newPassword2 =
c.readPassword("Enter new password again: ");
noMatch = ! Arrays.equals(newPassword1, newPassword2);
if (noMatch) {
c.format("Passwords don't match. Try again.%n");
} else {
change(login, newPassword1);
c.format("Password for %s changed.%n", login);
}
Arrays.fill(newPassword1, ' ');
Arrays.fill(newPassword2, ' ');
} while (noMatch);
}
Arrays.fill(oldPassword, ' ');
}
//Dummy change method.
static boolean verify(String login, char[] password) {
// this method always returns true in this example.
// modify this method to verify password according to your rules.
return true;
}
//Dummy change method.
static void change(String login, char[] password) {
// modify this method to change password according to your rules.
}
}
1153




被折叠的 条评论
为什么被折叠?



