java 利用FileOutputStream寫檔案(兩種方式)

憶江南的部落格發表於2015-09-07

java 利用FileOutputStream寫檔案(兩種方式)

作者:oyhk  2013-2-9 22:12:10  0  739


在Java中,FileOutputStream是一個位元組流類,用於處理原始二進位制資料。寫資料到檔案,你必須的資料轉換成位元組並將其儲存到檔案。見下面完整的示例。


package com.mkyong.io;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class WriteFileExample {
	public static void main(String[] args) {
 
		FileOutputStream fop = null;
		File file;
		String content = "This is the text content";
 
		try {
 
			file = new File("c:/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();
			}
		}
	}
}
下面是jdk7的新方法,寫入檔案例子:



package com.mkyong.io;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class WriteFileExample {
	public static void main(String[] args) {
 
		File file = new File("c:/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();
		}
	}
}

相關文章