首页 > 编程语言 > 详细

java读写文件样例

时间:2015-06-19 13:47:09      阅读:237      评论:0      收藏:0      [点我收藏+]
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class file {
 public static void main(String[] args) {
  try{
  
//System.out.println(BufferedReaderTest());


//BufferedWriterTest("hello,world");
 

 //appendMethodA("1.txt","hello");
 

 //appendMethodB("1.txt","hello");
 
 }catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 public static String BufferedReaderTest() throws IOException{
  FileReader fr=new FileReader("1.txt");
  BufferedReader br=new BufferedReader(fr);
  String s="";
  String a=br.readLine();
  while(a!=null)
  {
   s=s+a;
   a=br.readLine();
  }
  br.close();
  fr.close();
  return s;
    }
 public static void BufferedWriterTest(String s) throws IOException{
  FileWriter fw=new FileWriter("1.txt");  
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(s);
        bw.close();
        fw.close();
    }
  public static void appendMethodB(String fileName, String content) {
         try {
             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
                 
             FileWriter writer = new FileWriter(fileName, true);
             writer.write(content);
             writer.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
  public static void appendMethodA(String fileName, String content) {
         try {
             // 打开一个随机访问文件流,按读写方式
                        
             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
             // 文件长度,字节数
              
             long fileLength = randomFile.length();
             //将写文件指针移到文件尾。
             
             randomFile.seek(fileLength);
             randomFile.writeBytes(content);
             randomFile.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
}

java读写文件样例

原文:http://my.oschina.net/u/1248318/blog/468771

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!