【Java开源代码栏目提醒】:网学会员鉴于大家对Java开源代码十分关注,论文会员在此为大家搜集整理了“TextSuperaddition.java”一文,供大家参考学习
package com.zf.s10;//创建一个包
import java.io.FileWriter;//引入类
import java.io.IOException;
import java.io.RandomAccessFile;
public class TextSuperaddition {//将内容追加到文件尾部
//使用RandomAccessFile对象实现内容追加
public static void addFirst(String fileName){
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
long fileLength = randomFile.length();//获得文件字节数
randomFile.seek(fileLength);//将写文件指针移到文件尾。
String content="\nIf you would know the value of money, go and try to borrow some.\n" +
"要想知道钱的价值,就想办法去借钱试试。\n";
randomFile.write(content.getBytes("gb2312"));//内容写到文件内容尾部
randomFile.close();
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
}
//使用FileWriter对象实现内容追加
public static void addSecond(String fileName){
try {
//打开一个写文件器,true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
String content="That man is the richest whose pleasure are the cheapest. \n"+
"能处处寻求快乐的人才是最富有的人。\n";
writer.write(content);//内容写到文件内容尾部
writer.close();
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
}
public static void main(String[] args) {//java程序主入口处
String fileName = "F:/poem.txt";
System.out.println("1.RandomAccessFile对象实现内容追加:");
addFirst(fileName);//调用方法1
System.out.println("2.FileWriter对象实现内容追加:");
addSecond(fileName);//调用方法2
System.out.println("追后后文件内容显示:");
TextReadFile.readFileByLines(fileName);//调用TextReadFile类的按行读取文件方法
}
}