如何添加到文件尾:
* 默认的情况是,新内容覆盖旧内容。
* 添加到尾的两种方式
* 构造成器中指示定参数
* 使用随机文件
* 把第二个参数设为true
* new FileOutputStream(“a.txt”,true)
* 这样的弱点是:不能在旧的内容上修改,只能添加
随机读写
* 随机的含义
* 可以跳到任意位置读写
* 跳的单位是:字节
* 读写可以交替进行
* 使用类: RandomAccessFile
* 构造器
* (String name, String mode)
* 需要选定模式
* 可用的模式
* “r” 只能读,文件不存在会报错
* “rw” 读写方式,文件不存在会创建
* 二进制才能随机读写
* RandomAccessFile
* length() 文件长度
* seek(long pos) 文件指针定位
* 大量重载的 read 和 write
* 随机读写时是二进制的观点
* 为什么不能是文本的观点?行的长度可能不相等。
* 这个类并不能抽象为InputStream,或者OutputStream。流是个序列,不能随机访问。
java添加到文件尾的两种方式:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class AppendtoFile {
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();
}
}
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 readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
String fileName = "F:/私人物品刘梦冰/学习资料/exercise/Customer01.txt";
String content = "new append!";
//按方法A追加文件
AppendtoFile.appendMethodA(fileName, content);
AppendtoFile.appendMethodA(fileName, "append end. \n");
//显示文件内容
AppendtoFile.readFileByLines(fileName);
//按方法B追加文件
AppendtoFile.appendMethodB(fileName, content);
AppendtoFile.appendMethodB(fileName, "append end. \n");
//显示文件内容
AppendtoFile.readFileByLines(fileName);
}
}
运行结果:
最开始的文件:
添加内容后的文件: