字节流与字符流

字节流:字节输入流(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好用多了,特别是读取数据多的时候

 

posted @ 2015-06-15 11:42  雨下个不停  阅读(193)  评论(0编辑  收藏  举报