package txt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* 功能描写叙述:创建TXT文件并进行读、写、改动操作
* @author lizhiyong
* @version $Id: ReadWriteFile.java, v 0.1
2014年8月5日 下午1:27:38 Exp $
*/
public class ReadWriteFile {
//指定文件路径和名称
private static String path = "C:/測试.txt";
private static File filename = new File(path);
private static String readStr = " "; /**
* 创建文本文件.
* @throws IOException
*
*/
public static void creatTxtFile() throws IOException {
if (!filename.exists()) {
filename.createNewFile();
System.err.println(filename + "已创建! ");
} else {
filename.delete();
creatTxtFile();
}
} /**
* 读取文本文件.
* @throws UnsupportedEncodingException
*
*/
@SuppressWarnings("resource")
public static String readTxtFile() throws UnsupportedEncodingException {
String readData = null;
//BufferedReader br = null;
BufferedReader br = null;
try {
//br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
br = new BufferedReader(new FileReader(filename));
try {
while ((readData = br.readLine()) != null) {
System.out.println("readData:" + readData);
readStr = readStr + readData + "\r\n";
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} System.out.println("文件内容2是:" + "\r\n" + readStr);
return readStr;
} /**
* 给文件写内容.
* @param content 写入的文件内容
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void writeTxtFile(List contentList, HashMap<String, String> map)
throws IOException {
//先读取原有文件内容。然后进行写入操作
FileWriter writer = null;
String filein = map.get("1") + readStr + map.get("2") + readStr + map.get("3") + readStr
+ map.get("4");
try {
writer = new FileWriter(filename, true);
writer.write(filein);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} for (Iterator iterator = contentList.iterator(); iterator.hasNext();) {
HashMap<String, String> map2 = (HashMap<String, String>) iterator.next();
String name = map2.get("name");
String age = map2.get("age");
String postion = map2.get("postion");
String complit = map2.get("complit");
String filein1 = "\r\n" + name + readStr + age + readStr + postion + readStr + complit
+ "\r\n";
try {
writer = new FileWriter(filename, true);
writer.write(filein1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} } readTxtFile();
} /**
* 将文件里指定内容的第一行替换为其他内容.
*
* @param oldStr
* 查找内容
* @param replaceStr
* 替换内容
*/
@SuppressWarnings("unused")
public static void replaceTxtByStr(String oldStr, String replaceStr) {
String temp = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer(); // 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null && !temp.equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
} // 将内容插入
buf = buf.append(replaceStr); // 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
} br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* main方法測试
* @param s
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] s) throws IOException {
ReadWriteFile.creatTxtFile();
//ReadWriteFile.readTxtFile();
List list = new ArrayList();
HashMap<String, String> map = new HashMap<String, String>();
map.put("1", "姓名");
map.put("2", "年龄");
map.put("3", "职位");
map.put("4", "工作单位"); HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("name", "李四");
map2.put("age", "25");
map2.put("postion", "Java开发project师");
map2.put("complit", "上海汽车財务集团有限公司");
list.add(map2); HashMap<String, String> map3 = new HashMap<String, String>();
map3.put("name", "李四1");
map3.put("age", "251");
map3.put("postion", "Java开发project师1");
map3.put("complit", "上海汽车財务集团有限公司1");
list.add(map3); ReadWriteFile.writeTxtFile(list, map);
// ReadWriteFile.replaceTxtByStr("ken", "zhang");
}
}

生成和解析txt文件的更多相关文章

  1. dom4j生成和解析xml文件

    dom4j生成和解析xml文件 要生成和解析如下格式的xml文件: <?xml version="1.0" encoding="UTF-8"?> & ...

  2. python的OS模块生成100个txt文件

    #!/user/bin/env/python35 # -*-coding:utf-8-*- # author:Keekuun """ 问题:生成一个文件夹,文件夹下面生成 ...

  3. php 批量生成html、txt文件

    首先建立一个conn.php的文件用来链接数据库 <?php     $link = mysql_connect("mysql_host" , "mysql_use ...

  4. C++生成和解析XML文件

    1.xml 指可扩展标记语言(EXtensible Markup Language) 2.xml 是一种标记语言,类似html 3.xml 的设计宗旨是传输数据,而非显示数据 4.xml 标签没有被预 ...

  5. [java] java解析txt文件

    /** * 读取txt文件内容封装为map返回 * @param filePath * @return */ public static String readTxt(String filePath) ...

  6. 【Java】使用Apache POI生成和解析Excel文件

    概述 Excel是我们平时工作中比较常用的用于存储二维表数据的,JAVA也可以直接对Excel进行操作,分别有jxl和poi,2种方式. HSSF is the POI Project's pure ...

  7. C#生成、解析xml文件以及处理报错原因

    转载自:http://blog.csdn.net/lilinoscar/article/details/21027319 简单的介绍一下生成XML文件以及解析,因为有些数据不一定放到数据库,减少链接数 ...

  8. 解析oui.txt文件,通过MAC前缀获取Organization

    1.前言 OUI是指Organizationally unique identifier  (组织唯一标识符),签发给各类组织的唯一标识符.MAC地址共有6个字节48位组成,前3个字节体现了OUI,其 ...

  9. js生成txt文件

    HTML CODE: <div class="modal-footer"> <a onfocus="this.blur();" id=&quo ...

随机推荐

  1. Python文件指针与Python函数

    文件内指针移动:f.seek() 强调:只有t模式下read(n),n代表字符的个数,除此以外都是以字节为单位. """ 文件内容:哈哈哈哈 呵呵呵呵 "&qu ...

  2. pytorch 加载数据集

    pytorch初学者,想加载自己的数据,了解了一下数据类型.维度等信息,方便以后加载其他数据. 1 torchvision.transforms实现数据预处理 transforms.Totensor( ...

  3. UIBarButtonSystemItem 样式

    使用时需要注意创建方式的区别: 01 typedef enum { 02     UIBarButtonSystemItemDone, 03     UIBarButtonSystemItemCanc ...

  4. Codeforces Round #879 (Div. 2) C. Short Program

    题目链接:http://codeforces.com/contest/879/problem/C C. Short Program time limit per test2 seconds memor ...

  5. Luogu 2216 [HAOI2007]理想的正方形 (单调队列优化)

    题意: 给出一个 N×M 的矩阵,以及一个数值 K ,求在给定的矩阵中取出一个 K×K 的矩阵其中最大值减去最小值的最小值. 细节: 没有细节来发暴力走天下,20分也是分啊~~~ QAQ. 分析: 感 ...

  6. 【LeetCode】Spiral Matrix(螺旋矩阵)

    这是LeetCode里的第54道题. 题目要求: 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ...

  7. Oracle排错总结

    一.Oracle常规恢复之不安全恢复 http://www.cnblogs.com/jyzhao/p/4723994.html#2.11

  8. Java-将字符串转为数字

    package com.tj; public class MyClass implements Cloneable { public static void main(String[] args) { ...

  9. RHEL7网卡命名规则

    systemd 和 udev 引入了一种新的网络设备命名方式:一致网络设备命名(CONSISTENT NETWORK DEVICE NAMING).根据固件.拓扑.位置信息来设置固定名字,带来的好处是 ...

  10. Android从Fragment跳转到Activity

    代码改变世界 Android从Fragment跳转到Activity Intent intent = new Intent(getActivity(), LoginActivity.class); s ...