java向文件写数据的3种方式
来源:互联网 发布:软件项目检测合同范本 编辑:程序博客网 时间:2024/05/01 23:28
下边列举出了三种向文件中写入数据的方式,当然还有其他方式,帮助自己理解文件写入类的继承关系,分享出来供初学者使用。类的关系:
file->fileoutputstream->outputstreamWriter(FileWriter继承outputstreamWriter对象)
测试代码:
package com.test.csdn;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* 测试向文件中写文件
*
* @author rey
*
*/
public class TestWirteFile {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String sContent = "市场调研公司Forrester Research(以下简称“Forrester”)的分析师分析师莎拉·罗特曼-埃普斯(Sarah Rotman Epps)周四发布报告称,今年美国市场平板电脑销量将达到350万台。到2013年,美国平板电脑销售总量将超越台式机。";
String sDestFile = "/home/rey/temp/myWrite.txt";
File destFile = new File(sDestFile);
if (!destFile.exists()) {
destFile.createNewFile();
}
// 1.向文件写入内容
// writeByFileWrite(sDestFile, sContent);
// 2.FileOutputStream向文件写入内容
// writeByFileWrite(sDestFile, sContent);
// 2.OutputStreamWriter向文件写入内容
writeByOutputStreamWrite(sDestFile, sContent);
}
/**
* 用FileWrite向文件写入内容
*
* @param _destFile
* @throws IOException
*/
public static void writeByFileWrite(String _sDestFile, String _sContent)
throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter(_sDestFile);
fw.write(_sContent);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fw != null) {
fw.close();
fw = null;
}
}
}
/**
* 用FileOutputStream向文件写入内容
*
* @param _destFile
* @throws IOException
*/
public static void writeByFileOutputStream(String _sDestFile,
String _sContent) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_sDestFile);
fos.write(_sContent.getBytes());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fos != null) {
fos.close();
fos = null;
}
}
}
/**
* 用OutputStreamWrite向文件写入内容
*
* @param _destFile
* @throws IOException
*/
public static void writeByOutputStreamWrite(String _sDestFile,
String _sContent) throws IOException {
OutputStreamWriter os = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_sDestFile);
os = new OutputStreamWriter(fos, "UTF-8");
os.write(_sContent);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (os != null) {
os.close();
os = null;
}
if (fos != null) {
fos.close();
fos = null;
}
}
}
}
- java向文件写数据的3种方式
- java向文件写数据的3种方式
- Java向Excel文件中写数据
- Java向文件中写数据
- 向文件中写数据的方法
- 在Servlet中以下载的方式向浏览器写数据--中文文件乱码问题解决
- java写文件的几种方式
- java写文件的三种方式
- C语言中向屏幕写数据的诸多方式
- 向文件中写数据
- 向文件中写入数据读取数据的几种方式
- 控制器向视图传递数据的3种方式
- java 以追加的方式写文件
- Java写文件的方式-二进制文件
- java 向jsp页面写数据的时候出现乱码
- 向Ini文件中写入流数据
- 向文件中写数据,读数据
- android向文件指定位置写数据
- 一个月来的总结
- java web应用文件下载(包括中文文件名乱码处理)
- 正在进行生成的同时试图签出,因为无法对必须修改的文件"Web.config等"进行更改...
- 系鞋带的方法
- BlackBerry对于Web service的支持
- java向文件写数据的3种方式
- web开发
- Java API 文档 网址目录(中英文)
- IIS v5.1 "Http-500 服务器内部错误"解决办法
- 11.27 memcpy和memmove有什么区别?
- commons-fileupload上传,获取上传页面普通表单域的值
- Android程序内存管理必读
- 这是个WEB 问题 请问这个是什么 ??我是初学者
- 结构体指针变量与结构体成员指针变量