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. import java.io.*;
  8. public class Exercise {
  9. public static void main(String args[]) {
  10. FileOutputStream fos = null;
  11. File file;
  12. String mycontent = "This is my Data which needs to be written into the file.";
  13. try {
  14. // specify the file path
  15. file = new File("/home/zjz/Desktop/myFile.txt");
  16. fos = new FileOutputStream(file);
  17. /* This logic will check whether the file exists or not.
  18. if the file is not found at the specified location it would create
  19. a new file
  20. */
  21. // if (!file.exists()) {
  22. // file.createNewFile();
  23. // }
  24. /* String content cannot be directly written into a file.
  25. It needs to be converted into bytes
  26. */
  27. byte[] bytesArray = mycontent.getBytes();
  28. fos.write(bytesArray);
  29. fos.flush();
  30. System.out.println("File Written Successfully");
  31. } catch (FileNotFoundException e) {
  32. e.printStackTrace();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. } finally {
  36. try {
  37. if (fos != null) {
  38. fos.close();
  39. }
  40. } catch (IOException ioe) {
  41. System.out.println("Error in closing the Stream");
  42. }
  43. }
  44. }
  45. }


梅花香自古寒来