标签:
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();
}
}
}标签:
原文地址:http://my.oschina.net/u/1248318/blog/468771