两种方法Scanner和InputStreamReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class MainClass{
public static void method1(){
//use Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a number: ");
int num = scanner.nextInt();//获取整数值
System.out.print("Please input some characater: ");
String str = scanner.next();//获取字符串值
System.out.println("The string you input is: " + str);
}
public static void method2(){
//user BufferedReader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please input a number: ");
String str = reader.readLine();//获取字符串
int a = Integer.parseInt(str);//字符串转为数字
}catch(IOException e){
e.printStackTrace();
}
}
}
实例二:描述字符串写入文件
import java.io.*;
public class Test{
public static void main(String[] args){
try{
FileOutputStream out = new FileOutputStream("test.txt");
out.write("字符串写入文件".getBytes());
out.close();
}catch(IOException ioe){
}
}
}