您的位置:首页 > 其它

备份一下输出流,免得久不用忘记掉

2009-08-11 20:50 381 查看
 
import java.io.File;
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 {
public static void writeFileByBytes(String fileName) {
File file = new File(fileName);
OutputStream out = null;
try {
// 打开文件输出流
out = new FileOutputStream(file);
String content = "文件内容: 1,The First line; 2,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) {
e1.printStackTrace();
}
}
}
}
public static void writeFileByChars(String fileName) {
File file = new File(fileName);
Writer writer = null;
try {
// 打开文件输出流
writer = new OutputStreamWriter(new FileOutputStream(file));
String counter = "文件内容  1,The First line; 2,The second line.";
writer.write(counter);
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) {
e1.printStackTrace();
}
}
}
}
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 (IOException e) {
System.out.println("写文件 " + file.getAbsolutePath() + "失败!");
e.printStackTrace();
} finally {
if (writer != null) {
writer.close(); // 关闭输出文件流
}
}
}
public static void main(String[] args) {
String fileName = "d://Test//newTemp.txt";
WriteToFile.writeFileByBytes(fileName);
fileName = "d://Test//newTemp1.txt";
WriteToFile.writeFileByChars(fileName);
fileName = "d://Test//newTemp2.txt";
WriteToFile.writeFileByLines(fileName);
}
}


 

 

其实这么重要的东西,应该死记在心里的。不过记的东西太多了。还是放在BLOGGER上好了。呵呵。。BLOGGER,小仓库。。^^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  file string null import class
相关文章推荐