java字符串写入文件更加有效的写法
使用不用手动close;推荐FileWriter,代码更加简洁。
·
使用 try-with-resources 不用手动close;推荐FileWriter,代码更加简洁。
package util.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
public class StrWriteFileUtil {
/**
* FileWriter
* 覆盖写入,不用判断文件是否存在
*
* @param str
* @param path
*/
public static void write(String str, String path) {
try (FileWriter writer = new FileWriter(path)) {
writer.write("");//清空原文件内容
writer.write(str);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* FileWriter
* 写入 追加文件
*
* @param str
* @param path
*/
public static void writeAppend(String str, String path) {
try (FileWriter writer = new FileWriter(path, true)) {
writer.write(str);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* FileOutputStream
* 覆盖写入
*
* @param str
* @param path
*/
public static void outputStreamWrite(String str, String path) {
File txt = new File(path);
try (FileOutputStream fos = new FileOutputStream(txt)) {
if (!txt.exists()) {
txt.createNewFile();
}
byte[] bytes = str.getBytes();
int b = bytes.length; //是字节的长度,不是字符串的长度
fos.write(bytes, 0, b);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* FileOutputStream
* 写入 追加文件
*
* @param str
* @param path
*/
public static void outputStreamWriteAppend(String str, String path) {
File txt = new File(path);
try (FileOutputStream fos = new FileOutputStream(txt, true)) {
if (!txt.exists()) {
txt.createNewFile();
}
byte[] bytes = str.getBytes();
int b = bytes.length; //是字节的长度,不是字符串的长度
fos.write(bytes, 0, b);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String str = "hello world!";
String path = "./test/3.txt";
//write(str,path);
//writeAppend(str,path);
// outputStreamWrite(str, path);
outputStreamWriteAppend(str, path);
}
}
更多推荐
所有评论(0)