java FileOutputStream写入文件
2016-06-04 22:53
323 查看
FileOutputStream文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class writeFile { public static void writeFile(String filePath){ File file = new File(filePath); FileOutputStream fop=null; String content = "This is the text content"; try { fop= new FileOutputStream(file); //如果文件不存在则创建 if (!file.exists()) { file.createNewFile(); } // 将content存入字节数组中 byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes);//将contentInBytes字节数组中的内容写到输出流 fop.flush();//刷新此输出流并强制写出所有缓冲的输出字节 fop.close(); System.out.println("写入成功"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if (fop != null) { fop.close(); } }catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { String filePath="F:\\test\\testw.txt"; writeFile(filePath); } }
相关文章推荐
- SpringMVC之matrixVariable
- JAVA并发编程
- java web工程怎样改名
- 详解spring中每个jar包的作用
- java 实现n个整数的全排列
- java反射机制
- (45). Spring Boot MyBatis连接Mysql数据库【从零开始学Spring Boot】
- Struts2-学习笔记系列(15)-ajax支持和JSON
- Struts2-学习笔记系列(14)-拦截器
- Struts2-学习笔记系列(14)-拦截器
- Struts2-学习笔记系列(13)-类型转换异常和校验器
- Struts2-学习笔记系列(12)-set集合
- Struts2-学习笔记系列(12)-set集合
- Struts2-学习笔记系列(11)-使用StrutsTypeConverter
- java 实现二叉树的构建,先序,中序,后序,层次,递归,非递归的遍历
- Struts2-学习笔记系列(10)-自定义类型转换
- Struts2-学习笔记系列(10)-自定义类型转换
- java huffman树的构造和huffman编码
- java Web高并发解决方案
- java 图的邻接矩阵表示,深度优先遍历,广度优先遍历