首页 > 其他 > 详细

字节流与字符流

时间:2015-06-15 12:56:42      阅读:227      评论:0      收藏:0      [点我收藏+]

字节流:字节输入流(InputStream)、字节输出流(OutputStream)

public static void main(String[] args) throws Exception {
		
		File file = new File("D:" + File.separator + "test.txt");
		if (!file.getParentFile().exists()) { // 父路径不存在
			file.getParentFile().mkdirs(); // 创建目录
		}
		OutputStream output = new FileOutputStream(file) ;
		String str = "Hello World ." ;	// 要输出的数据
		byte [] data = str.getBytes() ;	// 字符串变为字节数组
		output.write(data); // 进行内容的输出操作,或者data等同于”HelloWorld”.getBytes()
	
		output.close(); 
	}

  

字符流:字符输入流(Reader)、字符输出流(Writer)主要处理中文 

 OutputStream输出有个缺点,如果要输出其他数据类型(int,double),只有转换成字节数组才能输出。因此,java提供了另一个输出PrintStream

public static void main(String[] args) throws Exception {
		PrintStream p = new PrintStream(new FileOutputStream(new File("D:"+ File.separator + "hello.txt")));
		p.print("Hello");
		p.println("World");
		util.close() ;
	}

  技术分享技术分享

通过观察PrintStream的结构与构造方法,这种是装饰设计模式。看起来类似代理设计模式,然而代理设计模式是基于接口,代理类所执行的方法也一定是接口中定义的方法

BufferedReader

public static void main(String[] args) throws Exception{
		BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream("d:" + File.separator + "test.txt")));
		String str = read.readLine();
		System.out.println(str);
		
	}

  

Scanner简单例子

public static void main(String[] args) throws Exception {
		Scanner scan = new Scanner(new FileInputStream(new File("D:"
				+ File.separator + "test.txt")));
		while(scan.hasNext()) {
			System.out.println(scan.next());
		}
		scan.close(); 
	}

Scanner比InputStream好用多了,特别是读取数据多的时候

 

字节流与字符流

原文:http://www.cnblogs.com/wujinsen/p/4576379.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!