Java将字符串写入文件,一般使用FileWriter或FileOutputStream类,下面分别给出示例:
一、使用FileWriter类
@Test
public void fileWriterTest() {
String str="hello world!\nhello world!\nhello world!";
FileWriter writer;
try {
writer = new FileWriter("testFileWriter.txt"); // 如果已存在,以覆盖的方式写文件
// writer = new FileWriter("testFileWriter.txt", true); // 如果已存在,以追加的方式写文件
writer.write(""); //清空原文件内容
writer.write(str);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
注意:如果使用追加的方式写文件,那么FileWriter的第2个参数要置为true。
二、使用FileOutputStream类
@Test
public void fileOutPutStreamTest() {
String str="hello world!\nhello world!\nhello world!";
File txt;
FileOutputStream fos;
try {
txt = new File("testFileOutPutStream.txt");
if(!txt.exists()) {
boolean newFile = txt.createNewFile();
if (!newFile) {
System.out.println("fail to create new file, please check!");
return;
}
}
byte[] bytes = str.getBytes();
int b = bytes.length; //是字节的长度,不是字符串的长度
fos = new FileOutputStream(txt); // 如果已存在,以覆盖的方式写文件
// fos = new FileOutputStream(txt, true); // 如果已存在,以追加的方式写文件
fos.write(bytes,0, b); // 写指定长度的内容
// fos.write(bytes); // 写全文
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
注意:如果使用追加的方式写文件,那么FileOutputStream的第2个参数要置为true。