您的位置:首页 > 其它

将内容追加到文件尾部-采用字符流的形式,将abc.txt中的内容更换为 好好学习,天天向上!

2015-09-24 20:13 337 查看
<span style="font-size:18px;">import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;

//采用字符流的形式,将abc.txt中的内容更换为  好好学习,天天向上!
public class Demo1 {
public static void main(String[] args) {
// fun1();
appendMethodA("./res/abc.txt", "!");
}

/**
* 最原始的添加办法
*/
private static void fun1() {
File file = new File("./res/abc.txt");
File file2 = new File("./res/ab.txt");
try (Reader is = new FileReader(file);
Writer os = new FileWriter(file2);) {
char[] buffer = new char[4];
int len = -1;
while ((len = is.read(buffer)) != -1)
os.write(buffer, 0, len);
os.write('!');
os.flush();
} catch (Exception e) {

}

file.delete();
file2.renameTo(new File("./res/abc.txt"));
}

/**
* 将内容追加到文件尾部A
*
* @param fileName
* @param content
*/
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 (Exception e) {
e.printStackTrace();
}
}

/**
* 将内容追加到文件尾部B
*
* @param fileName
* @param content
*/
public static void appendMethodB(String fileName, String content) {
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: