Java学习 - .txt文件读写类

同样为了考试而写= =
规定日志文件的字段数paraNum就可以使用了

public class TestLog {
	final int paraNum = 6;
	String[] args = new String[paraNum];
	// 操作类型
	// 用户名
	// 商品号
	// 数量
	// 金额
	// 时间
	
	public TestLog(String s) {
		this.valueOf(s);
	}
	
	public void valueOf(String s) {
		args = s.split("\\|");
	}
	
	public String toString() {
		String s = "";
		int first = 1;
		for(int i = 0; i < paraNum; ++i) {
			if(first == 1) first= 0;else s = s + "|";
			s = s + args[i];
		}
		return s;
	}

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class TXTutils {
	/*
	 * .txt file util class
	 */
	
	ArrayList<TestLog> arrayList = new ArrayList<>(); // store logs
	
	
	void read_process(String line) {
		/*
		 * add a line to arrayList
		 * Sample Parameters:
		 * line = "操作类型购买|用户名:popo|商品编号:001|数量:100|总金额:1000|时间:2001-01-24"
		 * 
		 * you should override the 'valueOf' method of 'TestLog'
		 */
		arrayList.add(new TestLog(line));
	}
	
	void write_process(BufferedWriter bw,String line) throws IOException {
		/*
		 * write a line to BufferedWriter
		 * Sample Parameters:
		 * line = "操作类型购买|用户名:popo|商品编号:001|数量:100|总金额:1000|时间:2001-01-24" 
		 */
		
		bw.write(line+"\n");
		bw.flush();
	}
	
	void readLogs(String path) {
		/*
		 * read .txt from path,store each line into arrayList
		 * Sample Parameters:
		 * path = "D:/logs.txt"
		 * 
		 * if file doesn't exist,this method will create a new file 
		 */
		
		File file = new File(path);
		
		if(! file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				JOptionPane.showConfirmDialog(null,"创建文件失败!","系统消息",JOptionPane.CLOSED_OPTION);
			}
		}
		
		try {
			InputStreamReader reader = new InputStreamReader(
					new FileInputStream(file)); 
			BufferedReader br = new BufferedReader(reader);
			
			String line = "";
			line = br.readLine();
			while(line != null) {
				read_process(line);
				line = br.readLine(); 
			}
			
			br.close();
		} catch (IOException e) {
			JOptionPane.showConfirmDialog(null,"文件读入错误", "系统错误",JOptionPane.CLOSED_OPTION);
		} 
	}
	
	
	void writeLogs(String path) {
		/*
		 * write data to .txt file
		 * Sample Parameters:
		 * path = "D:/logs.txt"
		 * 
		 * if file doesn't exist,this method will create a new file
		 */
		try {
			File file = new File(path);
			file.createNewFile();
			BufferedWriter bw = new BufferedWriter(
					new FileWriter(file)); 
			for(TestLog s : arrayList) {
				write_process(bw,s.toString());
			}
			
			bw.close();
		} catch (Exception e) {
			JOptionPane.showConfirmDialog(null,"文件写出错误", "系统错误",JOptionPane.CLOSED_OPTION);
		}
	}
	
}

posted @ 2020-12-26 09:04  popozyl  阅读(160)  评论(0编辑  收藏  举报