【java】File的使用:将字符串写出到本地文件,大小0kb的缘由

实现方法:app

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

public static void main(String[] args) { /** * ==============准备一些数据-start=============== */ String fileName = UUID.randomUUID().toString(); String filePath = "E:/sxContext"+ "/"+ fileName; String content = ""; StringBuilder stringBuilder = new StringBuilder(); 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 = new File(filePath); //若是父级文件件不存在 则新建立
        File parentFile = file.getParentFile(); if (!parentFile.exists()){ parentFile.mkdirs(); } FileWriter fw = null; BufferedWriter bw = null; try { if (!file.exists()){ file.createNewFile(); } fw = new FileWriter(file); bw = new BufferedWriter(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

 

【注意,ide

bw.write(content);

能够在for循环中屡次执行!!!测试

 

若是 担忧,能够在执行完bw.write()ui

执行:spa

bw.flush();

code

 

 

=======================blog

至于将文本内容写出到本地文件中,无论你写出的本地文件是否是txt文件或者没有后缀的文件,只要字符串

1.父级目录不存在,建立父级目录get

2.file文件判断exist() 若是没有就createNewFile()

3.将文本写出到本地

4.flush()

5.close()

 

出现本地文件0kb大小,可能会有如下几种缘由:

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

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

3.flush()方法能够不用执行 

相关文章
相关标签/搜索