Java寫檔案的三種方式
阿新 • • 發佈:2018-12-31
package file;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
public class Write_File
{
static FileOutputStream out ;
static FileOutputStream outSTr ;
static BufferedOutputStream Buff ;
static FileWriter fw ;
static int count=1000;//寫檔案行數
public static void main(String args[]) throws IOException
{
//可以用該方法記錄時間進行比較
long start = System.currentTimeMillis(); // 記錄起始時間
long end = System.currentTimeMillis(); // 記錄結束時間
System.out.println(end-start+"ms" );
//判斷輸出檔案是否存在
File file=new File("G:/xxx.txt");
if(!file.exists())
{
file.createNewFile();
}
//1. FileOutputStream 寫檔案
out = new FileOutputStream(new File("G:/xxx.txt"));
for (int i = 0; i < count; i++)
out.write("xxx" .getBytes());
out.close();
//2. BufferedOutputStream 寫檔案
outSTr = new FileOutputStream(new File("G:/xxx.txt"));
Buff=new BufferedOutputStream(outSTr);
// 等同於下面這行
// Buff=new BufferedOutputStream(new FileOutputStream(new File("G:/xxx.txt")));
for (int i = 0; i < count; i++)
Buff.write("xxx".getBytes());
Buff.flush();
Buff.close();
//3. FileWriter寫檔案
fw = new FileWriter("G:/xxx.txt");
for (int i = 0; i < count; i++)
fw.write("xxx");
fw.close();
}
}