Java输入输出

来源:互联网 发布:illustrator cs6 mac 编辑:程序博客网 时间:2024/06/08 06:39

读取输入

想要通过控制台进行输入,首先需要构造一个Scanner对象,并与“标准输入流”System.in关联。

Scanner in = new Scanner(System.in); 

现在,就可以使用Scanner类的各种方法实现输入操作了。例如,用nextLine方法将输入一行。

System.out.print("What's Your name?");String name=in.nextLine();

在这里,使用nextLine方法是因为在输入行中有可能包含空格。要想读取一个单词,就调用next()方法

String firstName = in.next();

想要读取一个整数,就调用nextInt()方法

System.out.print("How old are you?");int age = in.nextInt();

与此类似,想要读取下一个浮点数,就调用nextDouble方法。

程序清单

import java.util.Scanner;public class InOut {    public static void main(String[] args)    {        Scanner in=new Scanner(System.in);        //get first input        System.out.print("What's your name?");        String name=in.nextLine();//nextLine方法将输入一行        //get second input        System.out.println("How old are you?");        int age=in.nextInt();        //diplay output on console        System.out.println("Hello,"+name+",Next year,you'll be"+(age+1));           }}

注:因为输入是可见的,所以Scanner类不适用于从控制台读取密码。


格式化输出

1、用于printf的转换符

转换符 类型 举例 d 十进制整数 159 x 十六进制整数 9f o 八进制整数 237 f 定点浮点数 15.9 e 指数浮点数 1.59E+01 g 通用浮点数 —— a 十六进制浮点数 0x1.fccdp3 s 字符串 Hello c 字符 H b 布尔 True h 散列码 42628b2 tx 日期时间 —— % 百分号 % n 与平台有关的行分隔符 ——

文件输入与输出

  • 读取文件
    想要读取文件,需要用一个File对象构造一个Scanner对象,如下所示:
Scanner in=new Scanner(Paths.get("myfile.txt"));
  • 写入文件
    想要写入文件,需要构造一个PrintWriter对象。在构造器中,只需要提供文件名。
PrintWriter out=new PrintWriter("myfile.txt");

如果文件不存在,创建该文件。可以向输出到System.out 一样使用print、println以及printf命令。