java下载文件0kb_【java】File的使用:将字符串写出到本地文件,大小0kb的原因

实现方法:

暂时写一种方法,将字符串写出到本地文件,以后可以补充更多种方法:

8b7fff6de34622cccf06606e11fe6259e23.jpg

fd8630faec81d8be763815aa6b6fc219cb1.jpg

public static voidmain(String[] args) {/*** ==============准备一些数据-start===============*/String fileName=UUID.randomUUID().toString();

String filePath= "E:/sxContext"+ "/"+fileName;

String content= "";

StringBuilder stringBuilder= newStringBuilder();int a = 10;for (int i = 0; i < a; i++) {

stringBuilder.append(UUID.randomUUID().toString()+"\n\n");

}

content= "测试文本文件:\r\n" +stringBuilder.toString();/*** ==============准备一些数据-end===============*/

/*** ===============start-将字符串写出到本地文件=================*/File file= newFile(filePath);//如果父级文件件不存在 则新创建

File parentFile =file.getParentFile();if (!parentFile.exists()){

parentFile.mkdirs();

}

FileWriter fw= null;

BufferedWriter bw= null;try{if (!file.exists()){

file.createNewFile();

}

fw= newFileWriter(file);

bw= newBufferedWriter(fw);

bw.write(content);

bw.flush();

}catch(IOException e) {

e.printStackTrace();

}finally{try{

bw.close();

fw.close();

}catch(IOException e) {

e.printStackTrace();

}

}/*** ===============end-将字符串写出到本地文件=================*/}

View Code

【注意,

bw.write(content);

可以在for循环中多次执行!!!

如果 担心,可以在执行完bw.write()

执行:

bw.flush();

decadb48981233458cb5fb47ad8928af.png

=======================

至于将文本内容写出到本地文件中,不管你写出的本地文件是不是txt文件或者没有后缀的文件,只要

1.父级目录不存在,创建父级目录

2.file文件判断exist() 如果没有就createNewFile()

3.将文本写出到本地

4.flush()

5.close()

出现本地文件0kb大小,可能会有以下几种原因:

1.fileName 中也就是要创建的文件名  中包含了 非法字符,最常见的非法字符就是:冒号

0e03de6ff3b1a0d141fe48bc82a4bdee.png

2.要么就是没有执行close()正常关闭流

3.flush()方法可以不用执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值