Posted on 2009-05-24 21:21
啥都寫點 閱讀(152)
評論(0) 編輯 收藏 所屬分類:
J2SE
package book.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
/**
* 多種方式寫文件
*/
public class WriteToFile {
/**
* 以字節為單位寫文件。適合于寫二進制文件。如圖片等
* @param fileName 文件名
*/
public static void writeFileByBytes(String fileName){
File file = new File(fileName);
OutputStream out= null;
try {
// 打開文件輸出流
out = new FileOutputStream(file);
String content = "文件內容:\n1,The First line;\n2,The second line.";
byte[] bytes = content.getBytes();
//寫入文件
out.write(bytes);
System.out.println("寫文件" + file.getAbsolutePath() + "成功!");
} catch (IOException e){
System.out.println("寫文件" + file.getAbsolutePath() + "失??!");
e.printStackTrace();
} finally {
if (out != null){
try {
//關閉輸出文件流
out.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符為單位寫文件。
* @param fileName 文件名
*/
public static void writeFileByChars(String fileName){
File file = new File(fileName);
Writer writer = null;
try {
//打開文件輸出流
writer = new OutputStreamWriter(new FileOutputStream(file));
String content = "文件內容:\n1,The First line;\n2,The second line.";
writer.write(content);
System.out.println("寫文件" + file.getAbsolutePath() + "成功!");
} catch (IOException e){
System.out.println("寫文件" + file.getAbsolutePath() + "失敗!");
e.printStackTrace();
} finally {
if (writer != null){
try {
//關閉輸出文件流
writer.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行為單位寫文件
* @param fileName 文件名
*/
public static void writeFileByLines(String fileName){
File file = new File(fileName);
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileOutputStream(file));
//寫字符串
writer.println("文件內容:");
//能寫各種基本類型數據
writer.print(true);
writer.print(155);
//換行
writer.println();
//寫入文件
writer.flush();
System.out.println("寫文件" + file.getAbsolutePath() + "成功!");
} catch (FileNotFoundException e) {
System.out.println("寫文件" + file.getAbsolutePath() + "失??!");
e.printStackTrace();
} finally {
if (writer != null){
//關閉輸出文件流
writer.close();
}
}
}
public static void main(String[] args) {
String fileName = "c:/temp/tempfile0.txt";
WriteToFile.writeFileByBytes(fileName);
fileName = "c:/temp/tempfile1.txt";
WriteToFile.writeFileByChars(fileName);
fileName = "c:/temp/tempfile2.txt";
WriteToFile.writeFileByLines(fileName);
}
}
--
學海無涯