system.io java_java学习日记 System类对IO的支持

1、System.out

使用OutputStream向屏幕输出。

importjava.io.IOException;importjava.io.OutputStream;public classSystemoutDemo1 {public static voidmain(String[] args) {

OutputStream out= System.out; //此时的输出流是向屏幕上输出

try{

out.write("hello world!!!".getBytes());

}catch(IOException e) {

e.printStackTrace();

}try{

out.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

OutputStream的哪个子类为其实例化,就具备了向哪里输出的能力。如果使用了FileOutputStream则表示向文件输出,如果使用了System.out则表示向显示器输出,这里完全显示出了Java的多态性的好处,根据子类的不同完成的功能也不同。

2、System.err

System.err表示的是错误信息输出,如果程序出现错误,则可以直接使用System.err进行输出。

public classSystemerrDemo1 {public static voidmain(String[] args) {

String str= "hello";try{

System.out.println(Integer.parseInt(str));

}catch(Exception e){

System.err.println(e);

}

}

}

3、System.in

importjava.io.InputStream;public classSysteminDemo {public static void main(String[] args) throwsException {

InputStream input=System.in;

StringBuffer buf= newStringBuffer();

System.out.println("请输入内容:");int temp =0;while ((temp=input.read())!=-1){char c = (char) temp;if (c=='\n'){break;

}

buf.append(c);

}

System.out.println("输入的内容为:"+buf);

input.close();

}

}

如果输入中文会出现乱码。

4、BufferedReader类

键盘输入的标准格式:

importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;public classBufferReaderDemo1 {public static voidmain(String[] args) {

BufferedReader br= new BufferedReader(newInputStreamReader(System.in));

String str= null;

System.out.println("请输入内容:");try{

str=br.readLine();

}catch(IOException e) {

e.printStackTrace();

}

System.out.println("输入的内容为:"+str);

}

}

可以解决乱码问题。

5、Scanner类

importjava.util.Scanner;public classScannerDemo1 {public static voidmain(String[] args) {boolean flag = true;

System.out.println("请输入生日:");while(flag){

Scanner scanner= new Scanner(System.in);//从键盘输入数据

if (scanner.hasNext("\\d{4}-\\d{2}-\\d{2}")){

String bir= scanner.next("\\d{4}-\\d{2}-\\d{2}");

System.out.println("输入内容:"+bir);

flag=false;

}else{

System.out.println("输入格式错误");

}

}

}

}

scanner.userDelimiter  修改输入数据的分隔符

bbccf6f3ddf86a5231a6143e1d09f4b2.png

Scanner 输出文档的内容:

public classScannerDemo2 {public static voidmain(String[] args) {

File file= new File("d:"+File.separator+"demo"+File.separator+"test.txt");

Scanner scanner= null;try{

scanner= newScanner(file);

}catch(FileNotFoundException e) {

e.printStackTrace();

}

StringBuffer sbf= newStringBuffer();while(scanner.hasNext()){

sbf.append(scanner.next()).append("\n");

}

System.out.println(sbf);

}

}

6、对象序列化

java中共有两个标识接口:克隆(Cloneable)和对象序列化(Serializable)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值