码迷,mamicode.com
首页 > 其他好文 > 详细

。。。IO流的学习之一。。。

时间:2016-09-10 20:47:13      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

文件写入流FileWriter的使用:

 1 import static org.junit.Assert.*;
 2 
 3 import java.io.File;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 
 7 import org.junit.Test;
 8 
 9 
10 
11 public class MyTest {
12     //通过字符流写入数据到指定的文件中
13     @Test
14     public void testWrite() {
15         String path = "F:"+File.separator+"demo.txt";
16 //        如果文件不存在的话,就先创建这个文件
17         File file = new File(path);
18         if(!file.exists()){
19             try {
20                 file.createNewFile();
21             } catch (IOException e) {
22                 // TODO Auto-generated catch block
23                 e.printStackTrace();
24             }
25         }
26         FileWriter fileWriter = null;
27         try {
28             //在Windows中,一定要确保路径为path的文件是存在的
29             fileWriter = new FileWriter(path);
30             fileWriter.write("you are not a good boy!");
31             fileWriter.flush();
32             fileWriter.close();
33         } catch (IOException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         }finally{
37             //如果抛出异常的话,说明fileWriter对象时候创建不了的
38             if(fileWriter!=null){
39                 try {
40                     fileWriter.close();
41                 } catch (IOException e) {
42                     // TODO Auto-generated catch block
43                     e.printStackTrace();
44                 }
45             }
46             
47         }
48         
49         
50     }
51 
52 }

 

。。。IO流的学习之一。。。

标签:

原文地址:http://www.cnblogs.com/yingmeng/p/5860142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!