生成和解析txt文件

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"); } }


转载于:https://www.cnblogs.com/brucemengbm/p/7219059.html

Java解析TXT文件将其转换为JSON,通常需要两步操作:首先读取TXT文件内容,然后将数据结构化成可以序列化的JSON对象。这里提供一个简单的示例: ```java import com.google.gson.Gson; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TxtToJson { public static void main(String[] args) { try { // 读取TXT文件 BufferedReader reader = new BufferedReader(new FileReader("path_to_your_txt_file.txt")); // 定义一个临时的数据结构来存储TXT文件中的信息,例如每行是一个对象 String line; StringBuilder jsonContent = new StringBuilder(); while ((line = reader.readLine()) != null) { // 每行数据假设为键值对,用某种分隔符如逗号分割 String[] keyValue = line.split(","); MyObject obj = new MyObject(keyValue[0], keyValue[1]); // 自定义你的对象,比如MyObject // 将每个对象添加到列表中 List<MyObject> list = new ArrayList<>(); list.add(obj); // 使用Gson库将列表转换为JSON字符串 Gson gson = new Gson(); jsonContent.append(gson.toJson(list)).append("\n"); } reader.close(); // 输出生成的JSON字符串 System.out.println(jsonContent.toString()); } catch (IOException e) { e.printStackTrace(); } } } class MyObject { // 你需要定义一个映射TXT数据的对象 private String key; private String value; // 构造函数、gettersetter省略 } ``` 在这个例子中,你需要替换`path_to_your_txt_file.txt`为你的TXT文件路径,根据实际TXT文件的内容调整数据处理部分。这个过程假设TXT文件每一行都是键值对。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值