★☆

★☆
posts - 0, comments - 0, trackbacks - 0, articles - 80
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

读写文件

Posted on 2008-08-13 12:54 阅读(89) 评论(0)  编辑  收藏 所属分类: J2SM
读写文件:

//读文件,每次读一行
1)String s2 = new String();
 try{
 BufferedReader in = new BufferedReader( new FileReader("Degree.txt"));
 String s = new String();
 int j=0;
 while((s = in.readLine()) != null)
 {
 //处理..............
 }
 in.close();
     }catch(Exception ex){
 ex.printStackTrace();
     }

2)//读文件,每次读一个字符
StringBuffer br =new StringBuffer();
int i;
 try
 {
 FileInputStream cin =new FileInputStream("1.text");    
 while((i=cin.read())!=-1){
  br.append((char)i);
  }
 }catch (Exception e){
 ex.printStackTrace();
}
r=br.toString();
System.out.println(r);


//写文件
String[] s ={"123","456","789"};
try {
 FileWriter cout = new FileWriter("Employee.txt");
 cout.write(s[0]);
 cout.write("\r\n");
 cout.write(s[1]);
 cout.write("\r\n");
 cout.write(s[2]);
 cout.flush();
 cout.close();
 } catch (Exception e) {
 e.printStackTrace();
 }
}
//写文件
String s2="123\n456\n789";
 String s;
 try{
 BufferedReader in4 =new BufferedReader(new StringReader(s2));
 PrintWriter out1 =new PrintWriter(new BufferedWriter(new FileWriter("aa.text")));
 int lineCount = 1;
 while((s = in4.readLine()) != null){
 out1.println(lineCount++ + ":" + s);
 }
 out1.close();
 in4.close();
 }catch(Exception ex){
 System.out.println("End of stream"); 
}