File.newBufferedWriter(Java 8)
Files.write(Java 7)
PrintWriter
File.createNewFile
FileOutputStream.write(byte[] b) 管道流
package com.sixon.util;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* @author :sixon
* @date :2020/8/28 21:38
*/
public class NewFileUtils {
static String fileName = "path";
public static void createByNewBufferedWriter() throws IOException {
Path path = Paths.get(fileName);
//java8使用try-with-resources语法可以使继承Closeable接口的对象自动关闭
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)){
writer.write("创建并写入文件");
}
//追加模式
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)){
writer.write("追加模式-StandardOpenOption.APPEND");
}
}
public static void createByWrite() throws IOException {
//java7
Files.write(Paths.get(fileName),"创建文件并写入".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(fileName),"创建文件并写入".getBytes(StandardCharsets.UTF_8),StandardOpenOption.APPEND);
}
public static void createByPrintWriter() throws FileNotFoundException, UnsupportedEncodingException {
//java5按行写入
try(PrintWriter writer = new PrintWriter(fileName,"UTF-8")){
writer.println("创建文件");
writer.println("并按行写入");
}
/*java10开始支持StandardCharsets指定的标准字符集编码
try(PrintWriter writer = new PrintWriter(fileName, StandardCharsets.UTF_8)){
writer.println("创建文件");
writer.println("并按行写入");
}*/
}
public static void createByCreateNewFile() throws IOException {
File file = new File(fileName);
//文件不存在则创建并返回true,有则不创建并返回false,没有写入功能
if(file.createNewFile()){
System.out.println("文件创建成功");
}else if(!file.createNewFile()){
System.out.println("文件已存在,不会重复创建或覆盖");
}
try(FileWriter writer = new FileWriter(file)){
writer.write("写入方式");
}
}
public static void createByFileOutputStream() throws IOException {
//最原始也是最灵活
try(
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(fos);
//加缓冲用BufferedWriter
BufferedWriter bw = new BufferedWriter(osw);
//写二进制用ByteArrayOutPutStream
//写java对象用ObjectOutputStream
){
bw.write("创建文件并写入");
bw.flush(); //缓冲刷新
}
}
}