1. 程式人生 > >Java 寫一段字元到指定的文字文件中,如果該文字文件不存在,則建立該文字文件

Java 寫一段字元到指定的文字文件中,如果該文字文件不存在,則建立該文字文件

寫一段字元到指定的文字文件中,如果該文字文件不存在,則建立該文字文件

 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("\n\nOutputStream Closed."); 28 } 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 } 33 } 34 }

 

如果一開始,該文字文件不存在,那麼在執行程式之後,選中工程,按F5重新整理,該文字文件才會出現。