[Java] 如何写入文本文件

下面的代码创建一个文本文件,并写入一些内容。程序将会创建文件名为text.txt的文本文件

1 import java.io.BufferedWriter;
2  import java.io.FileWriter;
3 import java.io.File;
4 import java.io.Writer;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7
8 public class WriteTextFileExample
9 {
10 public static void main(String[] args)
11 {
12 Writer writer = null;
13
14 try
15 {
16 String text = "This is a text file";
17
18 File file = new File("write.txt");
19 writer = new BufferedWriter(new FileWriter(file));
20 writer.write(text);
21 } catch (FileNotFoundException e)
22 {
23 e.printStackTrace();
24 } catch (IOException e)
25 {
26 e.printStackTrace();
27 } finally
28 {
29 try
30 {
31 if (writer != null)
32 {
33 writer.close();
34 }
35 } catch (IOException e)
36 {
37 e.printStackTrace();
38 }
39 }
40 }
41 }
42

 

该例子来自:http://www.kodejava.org/examples/29.html

posted on 2010-07-01 13:14  Felix Liu  阅读(1388)  评论(0)    收藏  举报

导航