向指定文件目录下的文件写入内容

迈不过友情╰ 2022-08-21 13:50 331阅读 0赞

/**
* 向文件写入数据
* @param filePath 文件路径/文件名 例:D:/file/file.txt
* @param content 字符串
*/
public static void writeFile(String filePath, String content){

  1. FileWriter fw = null;
  2. try {
  3. File file = new File(filePath);
  4. //取得文件路径(例:D:/file)
  5. String path = filePath.substring(0, filePath.lastIndexOf("/"));
  6. File pathFile = new File(path);
  7. if(!pathFile.exists()){
  8. pathFile.mkdirs(); //如果路径不存在,则创建路径
  9. file.createNewFile(); //创建文件
  10. }
  11. fw = new FileWriter(file);
  12. fw.write(content); //向文件写入内容
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }finally{
  16. if(fw != null){
  17. try {
  18. fw.close();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. }

以上代码,如果采用fw = new FileWriter(file);的方式写文件,如果文件已经存在,则会覆盖文件之前的内容。如果想要在之前文件的基础上追加内容,则采用fw = new FileWriter(file,true);的方式。

发表评论

表情:
评论列表 (有 0 条评论,331人围观)

还没有评论,来说两句吧...

相关阅读