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. }