`
sharewind
  • 浏览: 156109 次
  • 性别: Icon_minigender_1
  • 来自: 福州
社区版块
存档分类
最新评论

java写文件和读文件

阅读更多

//=============================写文件

package fier;

import java.io.*;

public class write {

public static void main(String[] args) {
      write("E:\\123.txt", "hello");
}

public static void write(String path, String content) {
      String s = new String();
      String s1 = new String();
      try {
       File f = new File(path);
       if (f.exists()) {
        System.out.println("文件存在");
       } else {
        System.out.println("文件不存在,正在创建...");
        if (f.createNewFile()) {
         System.out.println("文件创建成功!");
        } else {
         System.out.println("文件创建失败!");
        }

       }
       BufferedReader input = new BufferedReader(new FileReader(f));

       while ((s = input.readLine()) != null) {
        s1 += s + "\n";
       }
       System.out.println("文件内容:" + s1);
       input.close();
       s1 += content;

       BufferedWriter output = new BufferedWriter(new FileWriter(f));
       output.write(s1);
       output.close();
      } catch (Exception e) {
       e.printStackTrace();
      }
}

}

//=============================读文件

package fier;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class sdsd {

/**
   * @param args
   */
public static void main(String[] args) {
   read("E:\\123.txt");
}

public static void read(String file) {
   String s = null;
   StringBuffer sb = new StringBuffer();
   File f = new File(file);
   if (f.exists()) {
    System.out.println("文件存在");

    try {
     BufferedReader br = new BufferedReader(new InputStreamReader(
       new FileInputStream(f)));

     while ((s = br.readLine()) != null) {
      sb.append(s);
     }
     System.out.println(sb);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }else{
    System.out.println("文件不存在!");
   }
}
}

分享到:
评论
2 楼 wangxc 2010-06-02  
楼主写的不错,受教啦!
1 楼 liangyicool 2009-01-04  
谢谢楼主分享 太感谢了  

相关推荐

Global site tag (gtag.js) - Google Analytics