登 录
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,小仓库。。^^
抱歉!评论已关闭.