Java字符串寫(xiě)入文件三種方式的實(shí)現(xiàn)
1、使用FileWriter
1
2
3
4
5
6
7
8
9
10
|
String str= "hello world!" ; FileWriter writer; try { writer = new FileWriter( "E:/token.txt" ); writer.write(str); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } |
2、使用FileOutPutStream
1
2
3
4
5
6
7
8
9
10
11
|
File txt= new File( "E:/log1.txt" ); if (!txt.exists()){ txt.createNewFile(); } byte bytes[]= new byte [ 512 ]; bytes=str.getBytes(); int b=bytes.length; //是字節(jié)的長(zhǎng)度,不是字符串的長(zhǎng)度 FileOutputStream fos= new FileOutputStream(txt); fos.write(bytes, 0 ,b); fos.write(bytes); fos.close(); |
3、使用FileOutPutStream追加寫(xiě)入文件
1
2
3
4
|
FileOutputStream fos = new FileOutputStream( "E:/log.txt" , true ); //true表示在文件末尾追加 fos.write(log.getBytes()); fos.close(); |
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://blog.csdn.net/fuyuwei2015/article/details/44257639