分類  >  編程 >

java 字元流writer、reader基本操作及了解

tags:    時間:2014-05-04 18:39:30
java 字元流writer、reader基本操作及理解

字元和位元組有什麼區別,額……這個我也不知道。

1、基本操作實例

import java.io.*;  public class CharDemo { 	public static void main(String[] args) 	{ 		File f=new File("F:\\workspace\\Javaprj\\test.txt"); 		 		Writer out=null; 		Reader in=null; 		try 		{ 			out=new FileWriter(f); 			String str="Hello World!!!"; 			out.write(str); 			System.out.println("The string "+"\"Hello World!!!\""+" has been written into "+f.getName()+"."); 			out.close(); 			 			in=new FileReader(f); 			char[] buf=new char[1024]; 			int num=in.read(buf); 			if(num!=-1) 			{ 				System.out.println("The string \""+ new String(buf,0,num) +"\" has been read from the file "+f.getName()+"."); 			} 			else 			{ 				System.out.println("The file \""+f.getName()+"\" is empty!"); 			} 		} 		catch(IOException e) 		{ 			e.printStackTrace(); 		} 	} }

2、注意的問題

將out.close();註釋掉

import java.io.*;  public class CharDemo { 	public static void main(String[] args) 	{ 		File f=new File("F:\\workspace\\Javaprj\\test.txt"); 		 		Writer out=null; 		Reader in=null; 		try 		{ 			out=new FileWriter(f); 			String str="Hello World!!!"; 			out.write(str); 			System.out.println("The string "+"\"Hello World!!!\""+" has been written into "+f.getName()+"."); 			//out.close(); 			 			in=new FileReader(f); 			char[] buf=new char[1024]; 			int num=in.read(buf); 			if(num!=-1) 			{ 				System.out.println("The string \""+ new String(buf,0,num) +"\" has been read from the file "+f.getName()+"."); 			} 			else 			{ 				System.out.println("The file \""+f.getName()+"\" is empty!"); 			} 		} 		catch(IOException e) 		{ 			e.printStackTrace(); 		} 	} }




推薦閱讀文章

Bookmark the permalink ,來源:互聯網