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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM