1、使用FileWriter
String str="hello world!";
FileWriter writer;
try {
writer = new FileWriter("E:/token.txt");
write.write("");//清空原文件内容
writer.write(str);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
2、使用FileWriter,追加写入文件
String str="hello world!";
FileWriter writer;
try {
writer = new FileWriter("E:/token.txt", true);
writer.write(str);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
3、使用FileOutPutStream
File txt=new File("E:/log1.txt");
if(!txt.exists()){
txt.createNewFile();
}
byte bytes[]=new byte[512];
bytes=str.getBytes();
int b=bytes.length; //是字节的长度,不是字符串的长度
FileOutputStream fos=new FileOutputStream(txt);
fos.write(bytes,0,b);
fos.write(bytes);
fos.close();
4、使用FileOutPutStream追加写入文件
File txt=new File("E:/log1.txt", true);
//true表示在文件末尾追加
if(!txt.exists()){
txt.createNewFile();
}
byte bytes[]=new byte[512];
bytes=str.getBytes();
int b=bytes.length; //是字节的长度,不是字符串的长度
FileOutputStream fos=new FileOutputStream(txt);
fos.write(bytes,0,b);
fos.write(bytes);
fos.close();