Java进阶(二十二)使用FileOutputStream写入文件
2016-01-12 12:02
615 查看
Java使用FileOutputStream写入文件
绪
在Java中,文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。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例如,使用新的“尝试资源关闭”的方法来轻松处理文件。
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(); } } }
参考文献
http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html美文美图
相关文章推荐
- Java进阶(二十二)使用FileOutputStream写入文件
- java中创建新进程的两种方法
- MySQL与Eclipse或者MyEclipse的连接
- Spring MVC 中 怎样从一个Controller 方法跳转到另一个方法,注意是跳转,不是调用
- 你不知道的JAVA
- 让JAVA代码跑得更快
- Struts2中DMI(动态方法调用)的一些问题
- 【JavaWeb Structs2学习】 用Action接受参数
- 关于Eclipse 插件添加右键菜单的三种方法
- 【Java基础 1】Java2平台的三个版本介绍
- 【Java 理论篇 1】Java2平台的三个版本介绍
- Struts2配置详解_配置Action
- Spring学习笔记---2.1-IOC容器解析Bean配置信息
- 深入讲解Struts2的用法
- JAVA相对路径、绝对路径
- java String 常用方法
- MyEclipse有关propedit editor插件的相关问题
- Android Studio使用SVN,与eclipse共同开发。
- eclipse-项目配置文件
- Java反射机制的使用