java文件写的四种方式
如下
FileWriter
public static void saveAsFileWriterByFileWriter(String path, String content) {
File file = new File(path);
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try (FileWriter fileWriter = new FileWriter(path, false);) {
fileWriter.write(content);
} catch (IOException ex) {
ex.printStackTrace();
}
}
RandomAccessFile
public static void saveAsRandomAccessFile(String path, String content) {
File file = new File(path);
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try(RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");){
randomAccessFile.writeBytes(content);
}catch (Exception exception){
exception.printStackTrace();
}
}
FileOutputStream
public static void saveAsFileOutputStream(String path, String content) {
File file = new File(path);
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try (FileOutputStream fileOutputStream = new FileOutputStream(file);) {
fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
} catch (Exception exception) {
exception.printStackTrace();
}
}
FileChannel
public static void saveAsFileChannel(String path, String content) {
File file = new File(path);
try {
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel fileChannel = fileOutputStream.getChannel();
) {
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
byteBuffer.put(content.getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
fileChannel.write(byteBuffer);
} catch (Exception exception) {
exception.printStackTrace();
}
}