使用 try-with-resources 不用手动close;推荐FileWriter,代码更加简洁。
package util.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
public class StrWriteFileUtil {
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();
}
}
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();
}
}
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();
}
}
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);
}
}



