Java创建文件并写入字符串

Java创建文件并写入字符串,如果文件存在则只写入字符串。

 
  1. String sourceString = "sourceString"; //待写入字符串

  2. byte[] sourceByte = sourceString.getBytes();

  3. if(null != sourceByte){

  4. try {

  5. File file = new File(path); //文件路径(路径+文件名)

  6. if (!file.exists()) { //文件不存在则创建文件,先创建目录

  7. File dir = new File(file.getParent());

  8. dir.mkdirs();

  9. file.createNewFile();

  10. }

  11. FileOutputStream outStream = new FileOutputStream(file); //文件输出流用于将数据写入文件

  12. outStream.write(sourceByte);

  13. outStream.close(); //关闭文件输出流

  14. } catch (Exception e) {

  15. e.printStackTrace();

  16. }

  17. }

猜你喜欢

转载自blog.csdn.net/qq_25600055/article/details/81381571
今日推荐