1.使用NIO的Files工具类
package file.io.append;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
/**
* @description:
* @author: LiYuan
* @date: 2024/7/19 14:42
*/
public class FilesTest {
public static void main(String[] args) throws Exception {
filesWrite();
}
public static void filesWrite() throws Exception {
String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
// 创建文件
// Files.createFile(Paths.get(path));
// 删除文件
// Files.delete(Paths.get(path));
// 写入字符串,覆盖写入;如果文件不存在,则新建文件
Files.write(Paths.get(path), "hello world".getBytes(StandardCharsets.UTF_8));
// 追加写入
Files.write(Paths.get(path), "\nthis is a good day".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
// 追加写入文件,第二个参数是可迭代的字符序列,指定编码,在每行后面自动添加换行符
Files.write(Paths.get(path), Collections.singleton("\none line"), StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// 追加写入文件,第二个参数是可迭代的字符序列,不指定编码,默认使用StandardCharsets.UTF_8
Files.write(Paths.get(path), Collections.singleton("two line"), StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}
}
write函数原型是:
public static Path write(Path path, byte[] bytes, OpenOption... options)
throws IOException;
public static Path write(Path path, Iterable<? extends CharSequence> lines,
Charset cs, OpenOption... options)
throws IOException;
public static Path write(Path path,
Iterable<? extends CharSequence> lines,
OpenOption... options)
throws IOException;
OpenOption是一个空接口,StandardOpenOption是一个实现了OpenOption的枚举类型:
public enum StandardOpenOption implements OpenOption {
/**
* Open for read access.
*/
READ,
/**
* Open for write access.
*/
WRITE,
/**
* If the file is opened for {@link #WRITE} access then bytes will be written
* to the end of the file rather than the beginning.
*
* <p> If the file is opened for write access by other programs, then it
* is file system specific if writing to the end of the file is atomic.
*/
APPEND,
/**
* If the file already exists and it is opened for {@link #WRITE}
* access, then its length is truncated to 0. This option is ignored
* if the file is opened only for {@link #READ} access.
*/
TRUNCATE_EXISTING,
/**
* Create a new file if it does not exist.
* This option is ignored if the {@link #CREATE_NEW} option is also set.
* The check for the existence of the file and the creation of the file
* if it does not exist is atomic with respect to other file system
* operations.
*/
CREATE,
/**
* Create a new file, failing if the file already exists.
* The check for the existence of the file and the creation of the file
* if it does not exist is atomic with respect to other file system
* operations.
*/
CREATE_NEW,
/**
* Delete on close. When this option is present then the implementation
* makes a <em>best effort</em> attempt to delete the file when closed
* by the appropriate {@code close} method. If the {@code close} method is
* not invoked then a <em>best effort</em> attempt is made to delete the
* file when the Java virtual machine terminates (either normally, as
* defined by the Java Language Specification, or where possible, abnormally).
* This option is primarily intended for use with <em>work files</em> that
* are used solely by a single instance of the Java virtual machine. This
* option is not recommended for use when opening files that are open
* concurrently by other entities. Many of the details as to when and how
* the file is deleted are implementation specific and therefore not
* specified. In particular, an implementation may be unable to guarantee
* that it deletes the expected file when replaced by an attacker while the
* file is open. Consequently, security sensitive applications should take
* care when using this option.
*
* <p> For security reasons, this option may imply the {@link
* LinkOption#NOFOLLOW_LINKS} option. In other words, if the option is present
* when opening an existing file that is a symbolic link then it may fail
* (by throwing {@link java.io.IOException}).
*/
DELETE_ON_CLOSE,
/**
* Sparse file. When used with the {@link #CREATE_NEW} option then this
* option provides a <em>hint</em> that the new file will be sparse. The
* option is ignored when the file system does not support the creation of
* sparse files.
*/
SPARSE,
/**
* Requires that every update to the file's content or metadata be written
* synchronously to the underlying storage device.
*
* @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a>
*/
SYNC,
/**
* Requires that every update to the file's content be written
* synchronously to the underlying storage device.
*
* @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a>
*/
DSYNC;
}
1.1 使用Files.newBufferedWriter追加写入
public static void bufferedWriter() throws Exception {
String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardOpenOption.APPEND)) {
bw.write("write file by bufferedWriter");
}
}
Files.bufferedWriter的函数原型是:
public static BufferedReader newBufferedReader(Path path, Charset cs)
throws IOException;
public static BufferedReader newBufferedReader(Path path) throws IOException;
public static BufferedWriter newBufferedWriter(Path path, Charset cs,
OpenOption... options)
throws IOException;
public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException;
1.2 小结
Files.write由于外部不能使用文件句柄,因此适合一次性写入,资源在函数内部打开和释放。
Files.bufferedWriter调用后,可以进行多次写入。
2 使用commos-io的FileUtils工具类
package file.io.append;
import org.apache.commons.io.FileUtils;
import java.io.File;
/**
* @description:
* @author: LiYuan
* @date: 2024/7/19 16:43
*/
public class FileUtilsTest2 {
public static void main(String[] args) throws Exception {
String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
FileUtils.writeStringToFile(new File(path), "hello world", "utf-8", true);
}
}
FileUtils.writeStringToFile有多个函数原型,可以写入字符序列、字符串、字节数组、集合,可以创建,追加等。
3 使用FileWriter
package file.io.append;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
/**
* @description:
* @author: LiYuan
* @date: 2024/7/19 16:58
*/
public class FileWriterTest {
public static void main(String[] args) throws Exception {
test1();
}
public static void test1() throws Exception {
String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (BufferedWriter bf = new BufferedWriter(new FileWriter(path, true))) {
bf.write("hello world");
}
}
public static void test2() throws Exception {
String path = "D:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (BufferedWriter bf = new BufferedWriter(new FileWriter(new File(path), true))) {
bf.write("hello world");
}
}
}
使用FileWriter不能指定文件编码。
4 使用FileOutputStream
package file.io.append;
import java.io.*;
public class FileOutputStreamTest {
public static void main(String[] args) throws Exception {
test1();
test2();
}
public static void test1() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true)))) {
bf.write("hello, world\n");
}
}
public static void test2() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(path, true))) {
bf.write("append new line".getBytes());
}
}
}
test1方法使用字符流的方式写入;
test2方法使用字节流的方式写入。
5 使用PrintWriter
package file.io.append;
import java.io.FileWriter;
import java.io.PrintWriter;
public class PrintWriterTest {
public static void main(String[] args) throws Exception {
test1();
}
public static void test1() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try(PrintWriter printWriter = new PrintWriter(new FileWriter(path, true))) {
printWriter.println("print by PrintWriter");
}
}
}
PrintWriter本身没有追加写的参数,但是可以通过创建对象的时候,参数使用Writer接口来适配。
package file.io.append;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class PrintWriterTest {
public static void main(String[] args) throws Exception {
// test1();
test2();
}
public static void test1() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try(PrintWriter printWriter = new PrintWriter(new FileWriter(path, true))) {
printWriter.println("\nprint by PrintWriter");
}
}
public static void test2() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try (PrintWriter p = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path, true)))) {
p.println("PrintWriter line2");
}
}
}
6 使用RandomAccessFile
package file.io.append;
import java.io.RandomAccessFile;
public class FileRandomAccessTest {
public static void main(String[] args) throws Exception {
test1();
}
public static void test1() throws Exception {
String path = "E:\\liyuan-gitee\\my-java-project\\myproj\\data\\file\\test1.txt";
try(RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw")) {
long length = randomAccessFile.length();
randomAccessFile.seek(length);
randomAccessFile.write("write by RandomAccessFile".getBytes());
}
}
}
先定位到文件末尾,然后写入。