IO流之打印流PrintStream和PrintWriter

      打印流主要用于输出,可以根据类型很方便的进行输出。打印流分为两种

字节打印流:PrintStream

字符打印流:PrintWriter

    下面来看看打印流的使用。

1.字节打印流:PrintStream

示例代码:

public class Test {

    public static void main(String[] args) {
      
    	 try {
    		 //构建一个字节输出流
		    OutputStream os=new FileOutputStream("L:\\test.txt");
			//构建缓冲流
			BufferedOutputStream bos=new BufferedOutputStream(os);
			//构建字节打印流
			PrintStream ps=new PrintStream(bos);
			//数据输出
			//println会换行输出,print不会换行
			ps.println(false);//写入boolean型
			ps.println("好好学习,天天向上");//写入字符串
			ps.println(3.1415926);//写入double类型
			
			ps.println(new person("小明", 20));//写入person类型
			//关闭流
			ps.close();
			bos.close();
			os.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
   
    }  
}
class person{
	String name;
	
	int age;
	
	person(String name,int age){
		this.name=name;
		this.age=age;
	}

	//记得重写toString方法,返回值即是写入的数据
	@Override
	public String toString() {
		return "person [name=" + name + ", age=" + age + "]";
	}
	
}

运行结果:



 

2.字符打印流:PrintWriter

示例代码:

public class Test {

    public static void main(String[] args) {
      
    	 try {
    		 //构建一个字符输出流
		    Writer os=new FileWriter("L:\\test.txt");
			//构建缓冲流
			BufferedWriter bos=new BufferedWriter(os);
			//构建字符打印流
			PrintWriter ps=new PrintWriter(bos);
			//println会换行输出,print不会换行
			ps.println(false);//写入boolean型
			ps.println("好好学习,天天向上");//写入字符串
			ps.println(3);//写入int类型
			
			ps.println(new person("小明明", 20));//写入person类型
			//关闭流
			ps.close();
			bos.close();
			os.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
   
    }  
}
class person{
	String name;
	
	int age;
	
	person(String name,int age){
		this.name=name;
		this.age=age;
	}

	//记得重写toString方法,返回值即是写入的数据
	@Override
	public String toString() {
		return "person [name=" + name + ", age=" + age + "]";
	}
	
}

运行结果:



 

可以看得出,使用打印流我们可以直接按照java的类型把数据写入,用起来非常方便。

猜你喜欢

转载自longpo.iteye.com/blog/2203600