文件写入流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 }
时间: 2024-11-09 23:37:22