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 修改输入数据的分隔符
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)。