Java字符串写入文件三种方式的实现
Java字符串写入文件三种方式的实现
1、使用FileWriter
Stringstr="helloworld!";
FileWriterwriter;
try{
writer=newFileWriter("E:/token.txt");
writer.write(str);
writer.flush();
writer.close();
}catch(IOExceptione){
e.printStackTrace();
}
2、使用FileOutPutStream
Filetxt=newFile("E:/log1.txt");
if(!txt.exists()){
txt.createNewFile();
}
bytebytes[]=newbyte[512];
bytes=str.getBytes();
intb=bytes.length;//是字节的长度,不是字符串的长度
FileOutputStreamfos=newFileOutputStream(txt);
fos.write(bytes,0,b);
fos.write(bytes);
fos.close();
3、使用FileOutPutStream追加写入文件
FileOutputStreamfos=newFileOutputStream("E:/log.txt",true);
//true表示在文件末尾追加
fos.write(log.getBytes());
fos.close();
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!