Java读写文本文件操作

 1 package com.test;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileWriter;
 8 import java.io.InputStreamReader;
 9 
10 /**
11  * Java读写文本文件操作
12  *
13  * @author penghuaiyi
14  * @date 2011-07-25
15  */
16 public class TextUtils {
17 
18     //读取文本文件
19     public static void readTxt(){
20         try {
21              File file = new File("c:/test.txt");
22              if (file.isFile() && file.exists()) {
23                 InputStreamReader read = new InputStreamReader(new FileInputStream(file));
24                 BufferedReader br = new BufferedReader(read);
25                 String lineTXT = null;
26                 while ((lineTXT = br.readLine()) != null) {
27                     System.out.println(lineTXT );
28                 }
29                 read.close();
30              }
31          } catch (Exception e) {
32              e.printStackTrace();
33          }
34     }
35 
36     //写入文本文件
37     public static void writeTxt(){
38         try{
39              File file = new File("c:/aa.txt");
40              if(!file.exists()){
41                  file.createNewFile();
42              }
43              FileWriter fw = new FileWriter(file);
44              BufferedWriter bw = new BufferedWriter(fw);
45              bw.write("aaaaaaaaa");
46              bw.newLine();
47              bw.write("bbbbbbbbb");
48              bw.flush();
49              bw.close();
50              fw.close();
51         }catch(Exception e){
52            e.printStackTrace();
53         }
54     }
55 
56     public static void main(String[] args) {
57         readTxt();
58         writeTxt();
59     }
60 
61 }

 

posted @ 2016-09-02 14:35  刘小神  阅读(732)  评论(0编辑  收藏  举报