求助,关于txt文件内容的处理

Anapeach 2017-08-27 02:43:58
如果我要把txt文件中上面的内容格式化成下面那种形式在屏幕上输出,不用改动txt文件内容,应该怎么做?求大神指点迷津
...全文
263 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
Freefish1994 2017-08-28
  • 打赏
  • 举报
回复
写了一个,不过只是针对你贴出来的这个内容格式的 还有就是输出的文本没像你的图片那样每列左对齐

public class Test {

	public static void main(String[] args) {
		String filePath = "";// txt文件路径
		for (String entity : getResult(getContent(filePath)))
			System.out.println(entity);
	}

	private static ArrayList<String> getContent(String filepath) {
		try {
			String temp = null;
			File file = new File(filepath);
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), "GBK");
			ArrayList<String> contentByLine = new ArrayList<String>();
			BufferedReader reader = new BufferedReader(read);
			while ((temp = reader.readLine()) != null && !"".equals(temp)) {
				contentByLine.add(temp);
			}
			read.close();
			return contentByLine;
		} catch (Exception e) {
			return null;
		}
	}

	private static List<String> getResult(List<String> txtContent) {
		List<String> result = new ArrayList<String>();
		String[] temp = null;
		StringBuilder sb = new StringBuilder();
		for (String entity : txtContent) {
			temp = entity.split(":");
			for (int i = 2; i <= 4; i++)
				sb.append(temp[i] + " ");
			sb.append(temp[0] + " ");
			sb.append(temp[1] + " ");
			for (int i = 5; i <= 7; i++)
				sb.append(temp[i] + " ");
			result.add(sb.toString());
			sb.delete(0, sb.length());
		}
		return result;
	}

}
Anapeach 2017-08-28
  • 打赏
  • 举报
回复
问题解决了,分析了楼上大神的代码,发现只要在封装类的toString方法里做点改动就可以了
rickylin86 2017-08-28
  • 打赏
  • 举报
回复
rickylin86 2017-08-28
  • 打赏
  • 举报
回复

import java.util.Comparator;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import java.nio.file.Path;
import java.nio.file.Paths;

import java.io.IOException;


public class StaffParser{
	public static void main(String[] args){
		Path path = Paths.get(System.getProperty("user.dir")).resolve("staffs.txt");
		ArrayList<Staff> staffs = loadFile(path);
		for(Staff staff : staffs){
			System.out.println(staff);
		}
	}

	private static ArrayList<Staff> loadFile(Path path){
		ArrayList<Staff> staffs = new ArrayList<>();
		//111:02-98781999:Williams:Nick:T:35:Computer Officer:14-10-2000 
		String regex = "^(?<id>\\d+):(?<tel>[-\\d]+):(?<firstname>\\w+):(?<lastname>\\w+):(?<remark>\\w+):(?<departmentID>\\d+):(?<department>[^:]+):(?<birthday>\\S+)\\s*$";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher= null;
		Staff staff = null;
		try(Scanner source = new Scanner(path);){
			String line = null;
			while(source.hasNextLine()){
				line = source.nextLine();
				matcher = pattern.matcher(line);
				if(matcher.matches()){
					staff = new Staff(matcher.group("id"),matcher.group("tel"),matcher.group("firstname"),matcher.group("lastname"),matcher.group("remark"),matcher.group("departmentID"),matcher.group("department"),matcher.group("birthday"));
					staffs.add(staff);
				}
			}
		}catch(IOException e){
			e.printStackTrace();
			System.exit(1);
		}
		staffs.sort(new StaffComparator());
		return staffs;
	}
}

class Staff{

	public Staff(String id,String tel,String firstname,String lastname,String remark,String departmentID,String department,String birthday){
		this.id = id;
		this.tel = tel;
		this.firstname = firstname;
		this.lastname = lastname;
		this.remark = remark;
		this.departmentID = departmentID;
		this.department = department;
		this.birthday = birthday;
	}
	
	@Override
	public String toString(){
		return String.format("%-10s%-10s%-5s%-4s%-15s%-7s%-20s%-13s",firstname,lastname,remark,id,tel,departmentID,department,birthday);
	}

	public String getCompareValue(){
		return firstname;
	}

	private String id;
	private String tel;
	private String firstname;
	private String lastname;
	private String remark;
	private String departmentID;
	private String department;
	private String birthday;
}

class StaffComparator implements Comparator<Staff>{
	public int compare(Staff staff1,Staff staff2){
		assert (staff1 != null) && (staff2 != null);
		return staff1.getCompareValue().compareTo(staff2.getCompareValue());
	}
}
result: ---------- java ---------- Anderson Sarah K 236 02-95437869 19 CEO 21-09-1988 Brown Sarah B 112 02-99893878 12 Electrician 09-02-1992 Chen Xiao Y 059 02-95673455 26 Consultant 01-05-2003 Coles David M 553 03-99999999 12 Manager 12-12-1999 Couch David A 131 02-95673456 26 Consultant 23-04-1994 Jones Sarah B 869 02-95671660 45 Sales Manager 14-12-1995 Miller Sam B 372 02-12345678 22 Engineer 12-03-1998 Smith John C 148 02-93272658 43 Technical Manager 21-10-1988 Wang Mengjie X 619 02-95436669 26 Consultant 12-02-2001 Williams Nick T 111 02-98781999 35 Computer Officer 14-10-2000 Xue Fei L 812 02-98781987 35 Computer Officer 10-08-1998 Output completed (0 sec consumed) - Normal Termination
Freefish1994 2017-08-28
  • 打赏
  • 举报
回复
引用 8 楼 Anapeach 的回复:
自己写了一个,可以实现排序但是无法左对齐处理
public static void formatPrintAll() {
        try {
            FileReader fr = new FileReader("H:\\Test\\test.txt");
            BufferedReader bf = new BufferedReader(fr);
            String line;
            String s;

            ArrayList<String> al = new ArrayList<>();
            TreeSet<FormatEmployee> ts = new TreeSet<>();
            FormatEmployee e ;
            while ((line = bf.readLine()) != null) {
                al.add(line);
            }
            bf.close();
            fr.close();
            for (int i = 0; i < al.size(); i++) {
                s = al.get(i);
                String[] s1 = s.split(":");

                e = new FormatEmployee(s1[2], s1[3], s1[4], s1[0], s1[7], s1[5], s1[6], s1[1]);
                ts.add(e);
               //System.out.println(e);
            }                  
           ts.forEach(System.out::println);
            }
        } catch (IOException e) {
            System.out.print("文件不存在!");
        }
    }
早晨没有时间没有来及写,后来又写了一个对齐方式的方法,楼主可以参考参考 封装类用的你的那个,我加了get/set方法toString空格的设置改了一下

public class Test {

	public static void main(String[] args) {
		String filePath = "D:/1.txt";// txt文件路径
		Set<FormatEmployee> formatEmployees = format(getResult(getContent(filePath)));
		for(FormatEmployee entity : formatEmployees)
			System.out.println(entity);
	}

	/**
	 * 读取txt文件内容
	 * @param filepath 文件路径
	 * @return
	 */
	private static List<String> getContent(String filepath) {
		try {
			String temp = null;
			File file = new File(filepath);
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), "GBK");
			List<String> contentByLine = new ArrayList<String>();
			BufferedReader reader = new BufferedReader(read);
			while ((temp = reader.readLine()) != null && !"".equals(temp)) {
				contentByLine.add(temp);
			}
			reader.close();
			read.close();
			return contentByLine;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 将读取出的内容作为封装对象存入Set中
	 * @param txtContent
	 * @return
	 */
	private static Set<FormatEmployee> getResult(List<String> txtContent) {
		FormatEmployee formatEmployee = null;
		Set<FormatEmployee> formatEmployees = new TreeSet<FormatEmployee>();
		for (String entity : txtContent) {
			String[] s1 = entity.split(":");
			formatEmployee = new FormatEmployee(s1[2], s1[3], s1[4], s1[0],
					s1[7], s1[5], s1[6], s1[1]);
			formatEmployees.add(formatEmployee);
		}
		return formatEmployees;
	}

	/**
	 * 对齐
	 * @param formatEmployees
	 * @return
	 */
	private static Set<FormatEmployee> format(Set<FormatEmployee> formatEmployees){
		// 出入最大的就是姓和部门这两个字段
		// 这里只对这两个字段进行调整,如果还有需要可以模仿这个继续加
		int lasNameMaxLength = 0;// 姓氏长度的最大值
		int jobTitleMaxLength = 0;// 部门长度的最大值
		StringBuilder sb = new StringBuilder();
		// 获取内容中姓氏长度的最大值
		for(FormatEmployee entity : formatEmployees){
			if(entity.getLasName().length() > lasNameMaxLength)
				lasNameMaxLength = entity.getLasName().length();
		}
		// 获取内容中部门长度的最大值
		for(FormatEmployee entity : formatEmployees){
			if(entity.getJobTitle().length() > jobTitleMaxLength)
				jobTitleMaxLength = entity.getJobTitle().length();
		}
		for(FormatEmployee entity : formatEmployees){
			// 将小于最大值的值根据差几个用空格补齐
			if(entity.getLasName().length() < lasNameMaxLength){
				for(int i = 0; i < lasNameMaxLength - entity.getLasName().length(); i++)
					sb.append(" ");
			}
			
			//补齐后统一加一个“\t”
			sb.append("\t");
			entity.setLasName(entity.getLasName() + sb.toString());
			sb.delete(0, sb.length());
		}
		for(FormatEmployee entity : formatEmployees){
			// 将小于最大值的值根据差几个用空格补齐
			if(entity.getJobTitle().length() < jobTitleMaxLength){
				for(int i = 0; i < jobTitleMaxLength - entity.getJobTitle().length(); i++)
					sb.append(" ");
			}
			
			//补齐后统一加一个“\t”
			sb.append("\t");
			entity.setJobTitle(entity.getJobTitle() + sb.toString());
			sb.delete(0, sb.length());
		}
		return formatEmployees;
	}
}

class FormatEmployee implements Comparable<FormatEmployee> {

	public String id; // 员工Number
	public String phoneNum; // 电话
	public String lasName; // 名
	public String firName; // 姓
	public String initial; // 中间名
	public String departNum; // 部门号
	public String jobTitle; // 部门
	public String date; // 入职日期

	public FormatEmployee(String lasName, String firName, String initial,
			String id, String date, String departNum, String jobTitle,
			String phoneNum) {
		this.id = id;
		this.phoneNum = phoneNum;
		this.lasName = lasName;
		this.firName = firName;
		this.initial = initial;
		this.departNum = departNum;
		this.jobTitle = jobTitle;
		this.date = date;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPhoneNum() {
		return phoneNum;
	}

	public void setPhoneNum(String phoneNum) {
		this.phoneNum = phoneNum;
	}

	public String getLasName() {
		return lasName;
	}

	public void setLasName(String lasName) {
		this.lasName = lasName;
	}

	public String getFirName() {
		return firName;
	}

	public void setFirName(String firName) {
		this.firName = firName;
	}

	public String getInitial() {
		return initial;
	}

	public void setInitial(String initial) {
		this.initial = initial;
	}

	public String getDepartNum() {
		return departNum;
	}

	public void setDepartNum(String departNum) {
		this.departNum = departNum;
	}

	public String getJobTitle() {
		return jobTitle;
	}

	public void setJobTitle(String jobTitle) {
		this.jobTitle = jobTitle;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	@Override
	public String toString() {
		return this.lasName + this.firName + "\t" + this.initial
				+ "\t" + this.id + "\t" + this.date + "\t" + this.departNum
				+ "\t" + this.jobTitle + this.phoneNum;
	}

	public int compareTo(FormatEmployee o) {
		return this.lasName.compareTo(o.lasName);
	}
}
Anapeach 2017-08-28
  • 打赏
  • 举报
回复
引用 4 楼 rickylin86 的回复:
把源文件里面的内容贴出来。明天写给你
在楼下
Anapeach 2017-08-28
  • 打赏
  • 举报
回复
111:02-98781999:Williams:Nick:T:35:Computer Officer:14-10-2000 112:02-99893878:Brown:Sarah:B:12:Electrician:09-02-1992 131:02-95673456:Couch:David:A:26:Consultant:23-04-1994 236:02-95437869:Anderson:Sarah:K:19:CEO:21-09-1988 553:03-99999999:Coles:David:M:12:Manager:12-12-1999 869:02-95671660:Jones:Sarah:B:45:Sales Manager:14-12-1995 148:02-93272658:Smith:John:C:43:Technical Manager:21-10-1988 372:02-12345678:Miller:Sam:B:22:Engineer:12-03-1998 059:02-95673455:Chen:Xiao:Y:26:Consultant:01-05-2003 812:02-98781987:Xue:Fei:L:35:Computer Officer:10-08-1998 619:02-95436669:Wang:Mengjie:X:26:Consultant:12-02-2001 这是源文件内容
rickylin86 2017-08-28
  • 打赏
  • 举报
回复
把源文件里面的内容贴出来。明天写给你
Anapeach 2017-08-28
  • 打赏
  • 举报
回复
package Menu;
/**
 * 格式化员工类
 */
public class FormatEmployee implements Comparable<FormatEmployee> {

    public String ID;         //员工Number
    public String phoneNum;    //电话
    public String lasName;    //名
    public String firName;    // 姓
    public String initial;    //中间名
    public String departNum;  // 部门号
    public String jobTitle;   // 部门
    public String date;        //入职日期

    public FormatEmployee(String lasName, String firName, String initial, String ID, String date, String departNum, String jobTitle, String phoneNum ) {
        this.ID = ID;
        this.phoneNum = phoneNum;
        this.lasName = lasName;
        this.firName = firName;
        this.initial = initial;
        this.departNum = departNum;
        this.jobTitle = jobTitle;
        this.date = date;
    }

    @Override
    public String toString() {
        return this.lasName+"\t\t\t"+this.firName+"\t\t"+this.initial+"\t"+this.ID+"\t"+this.date+"\t\t"+this.departNum+"\t"+this.jobTitle+"\t"+this.phoneNum;
    }

    @Override
    public int compareTo(FormatEmployee o) {
        return this.lasName.compareTo(o.lasName);
    }
}
Anapeach 2017-08-28
  • 打赏
  • 举报
回复
自己写了一个,可以实现排序但是无法左对齐处理
public static void formatPrintAll() {
        try {
            FileReader fr = new FileReader("H:\\Test\\test.txt");
            BufferedReader bf = new BufferedReader(fr);
            String line;
            String s;

            ArrayList<String> al = new ArrayList<>();
            TreeSet<FormatEmployee> ts = new TreeSet<>();
            FormatEmployee e ;
            while ((line = bf.readLine()) != null) {
                al.add(line);
            }
            bf.close();
            fr.close();
            for (int i = 0; i < al.size(); i++) {
                s = al.get(i);
                String[] s1 = s.split(":");

                e = new FormatEmployee(s1[2], s1[3], s1[4], s1[0], s1[7], s1[5], s1[6], s1[1]);
                ts.add(e);
               //System.out.println(e);
            }                  
           ts.forEach(System.out::println);
            }
        } catch (IOException e) {
            System.out.print("文件不存在!");
        }
    }
李德胜1995 2017-08-27
  • 打赏
  • 举报
回复
使用BufferedReader一行一行读取,使用split根据:把每一行拆分出来即可。。。。
Anapeach 2017-08-27
  • 打赏
  • 举报
回复
图片在二楼,新人求大神指点
Anapeach 2017-08-27
  • 打赏
  • 举报
回复

51,410

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧