写一段字符到指定的文本文档中,如果该文本文档不存在,则创建该文本文档
1 import java.io.File; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.OutputStream; 6 7 public class IOTest03 { 8 9 public static void main(String[] args) { 10 File dest = new File("dest.txt"); 11 OutputStream os = null; 12 13 try { 14 os = new FileOutputStream(dest, false); 15 String msg = "Hi, Good morning."; 16 byte[] buffer = msg.getBytes(); // encode 17 os.write(buffer, 0, buffer.length); 18 os.flush(); 19 } catch (FileNotFoundException e) { 20 e.printStackTrace(); 21 } catch (IOException e) { 22 e.printStackTrace(); 23 } finally { 24 try { 25 if (os != null) { 26 os.close(); 27 System.out.println(" OutputStream Closed."); 28 } 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 } 33 } 34 }
如果一开始,该文本文档不存在,那么在执行程序之后,选中工程,按F5刷新,该文本文档才会在工程目录中显示,双击可打开该文本文档。