Java使用FileOutputStream写入文件

From: http://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/

 

  1. /* 使用FileOutputStream写入文件,FileOutputStream的write() 方法只接受byte[] 类型
  2. 的参数,所以需要将string通过getBytes()方法转换为字节数组。
  3. 1、首先判断文件是否存在,不存在就新建一个
  4. 2、写入文件是以覆盖方式
  5. 3、文件不存在会自动创建,存在则会被重写
  6. */
  7.  
  8. import java.io.*;
  9.  
  10. public class Exercise {
  11.  
  12. public static void main(String args[]) {
  13. FileOutputStream fos = null;
  14. File file;
  15. String mycontent = "This is my Data which needs to be written into the file.";
  16. try {
  17. // specify the file path
  18. file = new File("/home/zjz/Desktop/myFile.txt");
  19. fos = new FileOutputStream(file);
  20. /* This logic will check whether the file exists or not.
  21. if the file is not found at the specified location it would create
  22. a new file
  23. */
  24. // if (!file.exists()) {
  25. // file.createNewFile();
  26. // }
  27. /* String content cannot be directly written into a file.
  28. It needs to be converted into bytes
  29. */
  30. byte[] bytesArray = mycontent.getBytes();
  31. fos.write(bytesArray);
  32. fos.flush();
  33. System. out.println("File Written Successfully");
  34. } catch (FileNotFoundException e) {
  35. e.printStackTrace();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. } finally {
  39. try {
  40. if (fos != null) {
  41. fos.close();
  42. }
  43. } catch (IOException ioe) {
  44. System. out.println("Error in closing the Stream");
  45. }
  46. }
  47. }
  48.  
  49. }

转载于:https://www.cnblogs.com/zhuyeshen/p/11434136.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值