Java学习-014-文本文件写入实例源代码(两种写入方式)
此文源码主要为应用 Java 读取文本文件内容实例的源代码。若有不足之处,敬请大神指正,不胜感激!
第一种:文本文件写入,若文件存在则删除原文件,并重新创建文件。源代码如下所示:
/**
* @function 文本文件操作:写入数据
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium main.java.aaron.java.tools FileUtils.java txtWrite, 2015-2-2 21:03:53 Exp $
*
* @param filename :文本文件全路径
* @param encoding :编码格式
* @param fileContent :写入内容
*
* @return boolean 写入成功返回true
*
* @throws IOException
*/
public boolean txtWrite(String filename, String encoding, String fileContent){
// 先读取源文件内容, 再进行写入操作
boolean flag = false; FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null; /* 创建文件(删除旧文件) */
if (!this.createFile(filename)) {
return flag;
} try{
File file = new File(filename); // 文件路径 if(file.isFile()){
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), encoding);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(fileContent);
bw.close(); flag = true;
}else{
this.message = "文件全路径非法。当前文件全路径为:" + filename;
this.logger.warn(this.message);
}
}catch(Exception ioe){
this.message = "写文件{" + filename + "}内容出错。" + ioe.getMessage();
this.logger.error(this.message);
}finally{
try {
if(pw != null){
pw.close();
}
if(fos != null){
fos.close();
}
if(br != null){
br.close();
}
if(fis != null){
fis.close();
}
} catch (Exception e) {
this.message = e.getMessage();
this.logger.error(this.message);
}
} return flag;
}
文本文件覆盖写入源代码
测试源码如下所示:
/**
* 测试:创建文件-FileUtils.textWrite(String, String, String)
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium test.java.aaron.java.tools FileUtilsTest.java test_txtWrite, 2015-2-2 22:09:51 Exp $
*/
@Test
public void test_txtWrite() {
this.message = "\n\n\n测试:FileUtils.textWrite(String, String, String)";
this.logger.debug(this.message); try{
this.fu = new FileUtils();
this.txtfileWrite = this.constantslist.PARAFILEPATH.get("OUT") + "txtfileWrite.txt"; // 文件名
this.message = "写入文件路径为:" + this.txtfileWrite; this.fu.createFile(this.txtfileWrite); for(int i = 0; i < 10; i++){
this.fu.txtWrite(this.txtfileWrite, "UTF-8", "显示追加的信息:" + i);
} LinkedList<String> contentlist = this.fu.txtRead(this.txtfileWrite, "UTF-8"); if(contentlist.size() > 0){
for(int i = 0; i < contentlist.size(); i++){
this.logger.debug(contentlist.get(i));
}
}
}catch(Exception ioe){
this.message = ioe.getMessage();
this.logger.error(this.message);
}
}
测试:文本文件覆盖写入
第二种:文本文件写入,依据用户的提示指令是否删除已存在的原文件。若删除原文件,则同第一种;若不删除原文件,则在原文件末尾追加内容。源代码如下所示:
/**
* @function 文本文件操作:写入数据
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium main.java.aaron.java.tools FileUtils.java txtWrite, 2015-2-2 21:10:53 Exp $
*
* @param filename :文本文件全路径
* @param delete : 是否删除旧文件
* @param encoding :编码格式
* @param fileContent :写入内容
*
* @return boolean 写入成功返回true
*
* @throws IOException
*/
public boolean txtWrite(String filename, boolean delete, String encoding, String fileContent){
// 先读取源文件内容, 再进行写入操作
boolean flag = false;
String temp = "";
String filecontent = ""; FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null; /* 文件创建:若删除源文件,则为覆盖写入;若不删除原文件,则为追加写入 */
if (!this.createFile(filename, delete)) {
return flag;
} try{
File file = new File(filename); // 文件路径 if(file.isFile()){
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr); // 获取文件原有的内容
for(; (temp = br.readLine()) != null;){
filecontent += temp + this.constantslist.LINESEPARATOR;
} fileContent = filecontent + fileContent; OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), encoding);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(fileContent);
bw.close(); flag = true;
}else{
this.message = "文件全路径非法。当前文件全路径为:" + filename;
this.logger.warn(this.message);
}
}catch(Exception ioe){
this.message = "写文件{" + filename + "}内容出错。" + ioe.getMessage();
this.logger.error(this.message);
}finally{
try {
if(pw != null){
pw.close();
}
if(fos != null){
fos.close();
}
if(br != null){
br.close();
}
if(fis != null){
fis.close();
}
} catch (Exception e) {
this.message = e.getMessage();
this.logger.error(this.message);
}
} return flag;
}
文本文件写入源代码:
测试源码如下所示:
/**
* 测试:FileUtils.textWrite(String, boolean, String, String)
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium test.java.aaron.java.tools FileUtilsTest.java test_txtWriteAppend, 2015-2-2 22:19:51 Exp $
*/
@Test
public void test_txtWriteAppend() {
this.message = "\n\n\n测试:FileUtils.textWrite(String, boolean, String, String)";
this.logger.debug(this.message); try{
this.fu = new FileUtils();
this.txtfileWrite = this.constantslist.PARAFILEPATH.get("OUT") + "txtfileWrite-append.txt"; // 文件名
this.message = "写入文件路径为:" + this.txtfileWrite; this.fu.createFile(this.txtfileWrite, false); for(int i = 0; i < 10; i++){
this.fu.txtWrite(this.txtfileWrite, false, "UTF-8", "显示追加的信息:" + i);
} LinkedList<String> contentlist = this.fu.txtRead(this.txtfileWrite, "UTF-8"); if(contentlist.size() > 0){
for(int i = 0; i < contentlist.size(); i++){
this.logger.debug(contentlist.get(i));
}
}
}catch(Exception ioe){
this.message = ioe.getMessage();
this.logger.error(this.message);
}
}
测试:文本文件写入
至此, Java学习-014-文本文件写入实例源代码(两种写入方式) 顺利完结,希望此文能够给初学 Java 的您一份参考。
最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^
Java学习-014-文本文件写入实例源代码(两种写入方式)的更多相关文章
- Java学习-019-Properties 文件读取实例源代码
在这几天的学习过程中,有开发的朋友告知我,每个编程语言基本都有相应的配置文件支持类,像 Python 编程语言中支持的 ini 文件及其对应的配置文件读取类 ConfigParse,通过这个类,用户可 ...
- Java学习-016-CSV 文件读取实例源代码
上文(CSV文件写入)讲述了日常自动化测试过程中将测试数据写入 CSV 文件的源码,此文主要讲述如何从 CSV 文件获取测试过程中所需的参数化数据.敬请各位小主参阅,若有不足之处,敬请大神指正,不胜感 ...
- Java学习-017-EXCEL 文件读取实例源代码
众所周知,EXCEL 也是软件测试开发过程中,常用的数据文件导入导出时的类型文件之一,此文主要讲述如何通过 EXCEL 文件中 Sheet 的索引(index)或者 Sheet 名称获取文件中对应 S ...
- Java多线程13:读写锁和两种同步方式的对比
读写锁ReentrantReadWriteLock概述 大型网站中很重要的一块内容就是数据的读写,ReentrantLock虽然具有完全互斥排他的效果(即同一时间只有一个线程正在执行lock后面的任务 ...
- Spring学习之Spring与Mybatis的两种整合方式
本机使用IDEA 2020.1.MySql 8.0.19,通过Maven进行构建 环境准备 导入maven依赖包 <dependencies> <dependency> < ...
- Java Callable接口与Future接口的两种使用方式
Java Callable.Future的两种使用方式Callable+Futurepublic class Test { public static void main(String[] args) ...
- RabbitMQ学习第二记:工作队列的两种分发方式,轮询分发(Round-robin)和 公平分发(Fair dispatch)
1.什么是RabbitMQ工作队列 我们在应用程序使用消息系统时,一般情况下生产者往队列里插入数据时速度是比较快的,但是消费者消费数据往往涉及到一些业务逻辑处理导致速度跟不上生产者生产数据.因此如果一 ...
- java多线程总结一:线程的两种创建方式及比较
1.线程的概念:线程(thread)是指一个任务从头至尾的执行流,线程提供一个运行任务的机制,对于java而言,一个程序中可以并发的执行多个线程,这些线程可以在多处理器系统上同时运行.当程序作为一个应 ...
- java多线程总结一:线程的两种创建方式及优劣比较
1.通过实现Runnable接口线程创建 (1).定义一个类实现Runnable接口,重写接口中的run()方法.在run()方法中加入具体的任务代码或处理逻辑. (2).创建Runnable接口实现 ...
随机推荐
- win8 中实现断点续传
1) Resume method does resume on cases where resume is possible. Meaning if the server accepts range- ...
- Dynamic LINQ OrderBy
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string pr ...
- Python 处理理时间超详细转的
# -*- coding: utf-8 -*- import time def timestamp_datetime(value): format = '%Y-%m-%d %H:%M:%S' ...
- winform学习之----打开文件对话框并将文件内容放入文本框
OpenFileDialog ofg = new OpenFileDialog(); ofg.Title = "ddd";//设置对话框标题 ofg.Multiselect = t ...
- JBPM表达业务流程(流程定义语言)
业务流程包括三部分: 活动 Activity / 节点 Node (有很多种,不同的类型有不同的功能,必须要有一个Start Activity) 连线 Transition / 转移 (从一个Acti ...
- FlyCapture2 fc2Image OpenCV IplImage Conversion 两种图像格式之间的转换
fc2Image是FlyCapture SDK的C语言库中的图片格式,由于在Windows上的MinGW无法编译FlyCapture2的C++库,只能使用C语言库,所以当我们在同时使用OpenCV的图 ...
- eval(gzinflate(base64_decode N层,自动解密
<?php header("Content-type: text/html; charset=utf-8"); $decode = 'DZdFEsRWEkT3vojt0EJM ...
- MHA监控进程异常退出
这两天遇到一个非常诡异的问题,打算和大家分享一下.只所以诡异估计是自己知识面不够吧.线上的MHA一直没有开启自动切换,都是手动切换的,最近开启了自动切换以后,退出securecrt窗口以后发现监控进程 ...
- php 实现qq第三方登录
学习之前,请大家先看一下oAuth协议. 首先呢,我们进入QQ互联的官方网站 http://connect.qq.com登入我们自己的QQ号,没有QQ号的小伙伴可以忽略本篇博文分享!
- POJ 3255 Roadblocks(A*求次短路)
Roadblocks Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 12167 Accepted: 4300 Descr ...