Java字符串写入文件三种方式的实现

2025-05-29 0 87

Java字符串写入文件三种方式的实现

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; //是字节的长度,不是字符串的长度

FileOutputStream fos=new FileOutputStream(txt);

fos.write(bytes,0,b);

fos.write(bytes);

fos.close();

3、使用FileOutPutStream追加写入文件

?

1

2

3

4
FileOutputStream fos = new FileOutputStream("E:/log.txt",true);

//true表示在文件末尾追加

fos.write(log.getBytes());

fos.close();

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/fuyuwei2015/article/details/44257639

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java字符串写入文件三种方式的实现 https://www.kuaiidc.com/115858.html

相关文章

发表评论
暂无评论