JAVA读取文件,排序再写出文件
?今天在百度知道看到这么一个问题
?
?
原问题链接:http://zhidao.baidu.com/question/219278917.html#here 读取TXT文件的格式为:字母 数字如: TOM 100 JACK 200 BILL 50 CATHY 150 然后按照数字大小排序(由大到小)输出TXT文件格式为: JACK 200 CATHY 150 TOM 100 BILL 50 问题补充:最后一行输出平均值=总和/人数如:平均值=(200+150+100+50)/4=125输出为一个新生成的TXT文件,不改变原文件如读取文件为test.txt, 输出文件为text1.txt??TOM 100JACK 200BILL 50CATHY 150/** * 读取文件内容 * * @param path * 路径 * @return 文件内容string * @author 金鑫 * @version 3.0 时间:2010年1月23日 14:56:44 */public static String getFileContent(String path){File file = new File(path);//分配新的直接字节缓冲区ByteBuffer byteBuffer = ByteBuffer.allocateDirect(186140);StringBuffer stringBuffer = new StringBuffer(186140);try{FileInputStream fileInputStream = new FileInputStream(file);//用于读取、写入、映射和操作文件的通道。FileChannel fileChannel = fileInputStream.getChannel();//编码字符集和字符编码方案的组合,用于处理中文,可以更改Charset charset = Charset.forName("GBK");while (fileChannel.read(byteBuffer) != -1){//反转此缓冲区byteBuffer.flip();CharBuffer charBuffer = charset.decode(byteBuffer);stringBuffer.append(charBuffer.toString());byteBuffer.clear();}fileInputStream.close();}catch (FileNotFoundException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}return stringBuffer.toString();}?@Testpublic void test(){String file = "D:/name.txt";String content = getFileContent(file);System.out.println(content);}?package com.feilong.common.io;/** * 用户 * * @author <a href="mailto:venusdrogon@163.com">金鑫</a> * @version 1.0 2011-1-25 上午10:03:47 */public class User{/** * 姓名 */private Stringname;/** * 数字 */private intcount;public String getName(){return name;}public void setName(String name){this.name = name;}public int getCount(){return count;}public void setCount(int count){this.count = count;}}?@Testpublic void test(){String file = "D:/name.txt";String content = getFileContent(file); //将内容以换行符转成数组String[] rowsContents = content.split("\r\n");//内容总共行数int rowCount = rowsContents.length;//总和int sum = 0;//最后一句话的数字 (200+150+100+50)StringBuilder lastRowOutBuilder = new StringBuilder();//集合 存储数据,这题最快的方法是用map 存储值,考虑到 扩展(是否姓名有重复,是否以后会增加属性字段)List<User> userList = new ArrayList<User>();for (int i = 0; i < rowCount; i++){String rowContent = rowsContents[i];String[] nameAndCount = rowContent.split(" ");User user = new User();user.setName(nameAndCount[0]);int count = Integer.parseInt(nameAndCount[1]);user.setCount(count);userList.add(user);sum += count;lastRowOutBuilder.append(count);if (i != rowCount - 1){lastRowOutBuilder.append("+");}}}?
import java.util.Comparator;/** * user 排序 * * @author <a href="mailto:venusdrogon@163.com">金鑫</a> * @version 1.0 2011-1-25 上午10:48:13 */public class UserComparator implements Comparator{/** *排序方式 * * @author <a href="mailto:venusdrogon@163.com">金鑫</a> * @version 1.0 2011-1-25 上午10:59:02 */public enum SortType{asc, desc}private SortTypesortType;public UserComparator(SortType sortType){this.sortType = sortType;}/* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */public int compare(Object arg0,Object arg1){User user0 = (User) arg0;User user1 = (User) arg1;int count0 = user0.getCount();int count1 = user1.getCount();switch (sortType) {case asc:if (count0 > count1){return 1;}else if (count0 < count1){return -1;}break;case desc:if (count0 > count1){return -1;}else if (count0 < count1){return 1;}break;default:break;}return 0;}}?Collections.sort(userList, new UserComparator(SortType.desc));?StringBuilder builder = new StringBuilder();for (int i = 0; i < userList.size(); i++){User user = userList.get(i);builder.append(user.getName());builder.append(" ");builder.append(user.getCount());builder.append("\r");}String outString = "平均值=(" + lastRowOutBuilder.toString() + ")/" + rowCount + "=" + sum / rowCount + "";builder.append(outString);System.out.println(builder.toString());?/** * 将字符串写到文件中 * * @param filePath * 文件路径 * @param content * 字符串内容 */public static void write(String filePath,String content){try{//向文本输出流打印对象的格式化表示形式//会自动创建文件,替换覆盖文字(非追加)PrintWriter printWriter = new PrintWriter(filePath);printWriter.write(content);printWriter.close();}catch (FileNotFoundException e){e.printStackTrace();}}?write("D:/2.txt", builder.toString());?@Testpublic void test(){String file = "D:/name.txt";String content = getFileContent(file);//将内容以换行符转成数组String[] rowsContents = content.split("\r\n");//内容总共行数int rowCount = rowsContents.length;//总和int sum = 0;//最后一句话的数字 (200+150+100+50)StringBuilder lastRowOutBuilder = new StringBuilder();//集合 存储数据,这题最快的方法是用map 存储值,考虑到 扩展(是否姓名有重复,是否以后会增加属性字段)List<User> userList = new ArrayList<User>();for (int i = 0; i < rowCount; i++){String rowContent = rowsContents[i];String[] nameAndCount = rowContent.split(" ");User user = new User();user.setName(nameAndCount[0]);int count = Integer.parseInt(nameAndCount[1]);user.setCount(count);userList.add(user);sum += count;lastRowOutBuilder.append(count);if (i != rowCount - 1){lastRowOutBuilder.append("+");}}//排序Collections.sort(userList, new UserComparator(SortType.desc));StringBuilder builder = new StringBuilder();for (int i = 0; i < userList.size(); i++){User user = userList.get(i);builder.append(user.getName());builder.append(" ");builder.append(user.getCount());builder.append("\r");}String outString = "平均值=(" + lastRowOutBuilder.toString() + ")/" + rowCount + "=" + sum / rowCount + "";builder.append(outString);System.out.println(builder.toString());write("D:/2.txt", builder.toString());}?User user = new User();
user.setName(nameAndCount[0]);
int count = Integer.parseInt(nameAndCount[1]);
user.setCount(count);
userList.add(user);
sum += count;
lastRowOutBuilder.append(count);
if (i != rowCount - 1){
lastRowOutBuilder.append("+");
}
}
}</pre>
?<br>
</div>
<div ");
builder.append(user.getCount());
builder.append("\r");
}
String outString = "平均值=(" + lastRowOutBuilder.toString() + ")/" + rowCount + "=" + sum / rowCount + "";
builder.append(outString);
System.out.println(builder.toString());</pre>
?</div>
<div ");
User user = new User();
user.setName(nameAndCount[0]);
int count = Integer.parseInt(nameAndCount[1]);
user.setCount(count);
userList.add(user);
sum += count;
lastRowOutBuilder.append(count);
if (i != rowCount - 1){
lastRowOutBuilder.append("+");
}
}
//排序
Collections.sort(userList, new UserComparator(SortType.desc));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < userList.size(); i++){
User user = userList.get(i);
builder.append(user.getName());
builder.append(" ");
builder.append(user.getCount());
builder.append("\r");
}
String outString = "平均值=(" + lastRowOutBuilder.toString() + ")/" + rowCount + "=" + sum / rowCount + "";
builder.append(outString);
System.out.println(builder.toString());
write("D:/2.txt", builder.toString());
}</pre>
?</div>
<div class="suply-content mt10">所有的完整代码,我传了附件</div>
<div class="suply-content mt10">这是用纯java自带的类做的,当然有更简单的,比如使用common-io</div>
</div>
<p>?</p>