package demo.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { /** * @param args */ public static void main(String[] args) { FileOutputStream fop = null; File file; String content = "This is the text content"; try { file = new File("C:\\users\\nopphanan7\\newfile.txt"); fop = new FileOutputStream(file); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { e.printStackTrace(); } } } }ผลลัพธ์ที่ได้คือ(ให้ไปดูที่ C:\\users\\....\\newfile.txt):
Done
ตัวอย่างเพิ่มเติมใน JDK 7 ใช้ try-with-resources เพื่อการ เปิด-ปิด อัตโนมัติ.
package demo.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { /** * @param args */ public static void main(String[] args) { File file = new File("C:\\users\\nopphanan7\\newfile.txt"); String content = "This is the text content"; try (FileOutputStream fop = new FileOutputStream(file)) { // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
ผลลัพธ์ที่ได้คือ(ให้ไปดูที่ C:\\users\\....\\newfile.txt)
Done
0 comments:
Post a Comment