- 浏览: 95884 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
yanbin0830:
繁体在liunx下,压缩解压完之后还是会出现乱码。可以试试
windows下文件名正常,但linux下用ZipOutputStream压缩后中文文件名乱码 -
oujunfeng:
介绍得很详细,赞一个要是格式上再好看点读着就没那么累了
海量数据处理汇总 -
tf03172003:
根本没有解答问题
一个线程进入一个对象的一个synchronized方法,其他线程是否还可以进入该对象的其他方法 -
jiage17:
我在东软某部门笔试真碰到了楼主说的这道题
一笔试小题---文件读写操作(希望对刚毕业找工作的朋友有所帮助) -
gordianyuan:
<pre name="code" c ...
一笔试小题---文件读写操作(希望对刚毕业找工作的朋友有所帮助)
题目:文件intel.txt,内容如下:
小王【空格】10000【回车】
小强【空格】12345【回车】
小张【空格】2342 【回车】
小强【空格】1030 【回车】
小周【空格】1020 【回车】
请编写一程序从test.txt中读取数据,并按数字大小排序后写入另一文件sun.txt(写入格式同上)
下面是自己编写的程序代码,小弟刚毕业所学有限所幸要求功能是实现了,然必定有不规范不合理之处还望大家多多指教修正!!(希望大家提供些更合理的排序)
------------------------------------------------------------------
import com.j2se.file.MyIntComparator;//自定义比较器
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.TreeMap;
/***
*读文件test.txt内容(文件内容格式: 小王【空格】10000【回车】
* 小强【空格】12345【回车】
*并对该文件内容按存款数排序,然后将其写入另一文件内
*
*****/
public class fileSort {
/*****
* 以行为单位读写文件
*@param fileName 源文件
*@param toFileName 目标文件
* ****/
public static void read_writeFile(String fileName,String toFileName){
File file = new File(fileName);
BufferedReader reader=null;
TreeMap<Integer,String> map = new TreeMap<Integer,String>(new MyIntComparator());
File toFile = new File(toFileName);
PrintWriter writer = null;
try{
System.out.println("------------------读文件开始-------------------------------");
System.out.println();
System.out.println("以行为单位读取文件内容,每次读取一整行");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
String[] ss = null;
int line = 1;
//一次读一行,直到读取为null
while((tempString = reader.readLine()) != null){
//显示行号
System.out.println("line number is "+line+"::"+tempString);
line++;
ss = tempString.split(" ");
int i = 0;
String value = ss[i];
int key =Integer.parseInt(ss[i+1]);
System.out.println("key is:"+key);
System.out.println("value is:"+value);
map.put(key, value);
}
System.out.println("------------------读文件结束-------------------------------");
System.out.println();
System.out.println("------------------写文件开始-------------------------------");
System.out.println("写文件开始:"+file.getAbsolutePath());
writer = new PrintWriter(new FileOutputStream(toFile));
if(map !=null){
Object key = null;
Object value = null;
// 使用迭代器遍历Map的键,根据键取值
Iterator it = map.keySet().iterator();
while (it.hasNext()){
key = it.next();
value = map.get(key);
System.out.println("key is :"+key);
System.out.println("vlaue is :"+value);
//能写各种基本类型数据
writer.print(value+" ");
writer.print(key+" ");
//换行
writer.println();
//写入文件
writer.flush();
}
System.out.println("写文件"+file.getAbsolutePath()+"成功!");
System.out.println("---------------------------写文件结束--------------------------");
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null){
try{
reader.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
if(writer !=null){
writer.close();
}
}
}
public static void main(String[] args){
String fileName = "D:/test.txt";
String toFileName = "D:/test1.txt";
fileSort.read_writeFile(fileName, toFileName);
}
}
----------------自定义比较器--------------------------------------
import java.util.Comparator;
/**
* 整数比较器,将整数按降序排列
*/
class MyIntComparator implements Comparator{
/**
* o1比o2大,返回-1;o1比o2小,返回1。
*/
public int compare(Object o1, Object o2) {
int i1 = ((Integer)o1).intValue();
int i2 = ((Integer)o2).intValue();
if (i1 < i2){
return 1;
}
if (i1 > i2){
return -1;
}
return 0;
}
}
上面是我的想法,可以解决TreeMap的key冲突问题
getInteger(temp);方法中我用的正则匹配。
恩,我不敢说 用String的split没有用StringTokenizer好,但是值得肯定的是他们都能实现不假。
我在百度摆了下,看了几篇相关文章感觉看后只是看到它们的些许不同,还是不能区别出来哪个好与坏。
还望牛牛们详细讲解下吧
呵呵 你看下所有回复贴吧,有两位写的很好很值得收藏,其中一位仁兄给了面向对象思想的程序段。
你说的要是就本题而言是对的,但是如果被读取文件包含数字重复字段就不适用了,我当时也是没注意到,
看来一些问题还是需要摆出来献丑的,经过高人的修正确实能学到许多
大哥,你这个方法不就是前面那个嘛,hashmap不能解决重复key值的问题
jdk1.5下面的一个sort
呵呵 熟悉下api
小王【空格】10000【回车】
小强【空格】12345【回车】
小张【空格】2342 【回车】
小强【空格】1030 【回车】
小周【空格】1020 【回车】
请编写一程序从test.txt中读取数据,并按数字大小排序后写入另一文件sun.txt(写入格式同上)
下面是自己编写的程序代码,小弟刚毕业所学有限所幸要求功能是实现了,然必定有不规范不合理之处还望大家多多指教修正!!(希望大家提供些更合理的排序)
------------------------------------------------------------------
import com.j2se.file.MyIntComparator;//自定义比较器
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.TreeMap;
/***
*读文件test.txt内容(文件内容格式: 小王【空格】10000【回车】
* 小强【空格】12345【回车】
*并对该文件内容按存款数排序,然后将其写入另一文件内
*
*****/
public class fileSort {
/*****
* 以行为单位读写文件
*@param fileName 源文件
*@param toFileName 目标文件
* ****/
public static void read_writeFile(String fileName,String toFileName){
File file = new File(fileName);
BufferedReader reader=null;
TreeMap<Integer,String> map = new TreeMap<Integer,String>(new MyIntComparator());
File toFile = new File(toFileName);
PrintWriter writer = null;
try{
System.out.println("------------------读文件开始-------------------------------");
System.out.println();
System.out.println("以行为单位读取文件内容,每次读取一整行");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
String[] ss = null;
int line = 1;
//一次读一行,直到读取为null
while((tempString = reader.readLine()) != null){
//显示行号
System.out.println("line number is "+line+"::"+tempString);
line++;
ss = tempString.split(" ");
int i = 0;
String value = ss[i];
int key =Integer.parseInt(ss[i+1]);
System.out.println("key is:"+key);
System.out.println("value is:"+value);
map.put(key, value);
}
System.out.println("------------------读文件结束-------------------------------");
System.out.println();
System.out.println("------------------写文件开始-------------------------------");
System.out.println("写文件开始:"+file.getAbsolutePath());
writer = new PrintWriter(new FileOutputStream(toFile));
if(map !=null){
Object key = null;
Object value = null;
// 使用迭代器遍历Map的键,根据键取值
Iterator it = map.keySet().iterator();
while (it.hasNext()){
key = it.next();
value = map.get(key);
System.out.println("key is :"+key);
System.out.println("vlaue is :"+value);
//能写各种基本类型数据
writer.print(value+" ");
writer.print(key+" ");
//换行
writer.println();
//写入文件
writer.flush();
}
System.out.println("写文件"+file.getAbsolutePath()+"成功!");
System.out.println("---------------------------写文件结束--------------------------");
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null){
try{
reader.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
if(writer !=null){
writer.close();
}
}
}
public static void main(String[] args){
String fileName = "D:/test.txt";
String toFileName = "D:/test1.txt";
fileSort.read_writeFile(fileName, toFileName);
}
}
----------------自定义比较器--------------------------------------
import java.util.Comparator;
/**
* 整数比较器,将整数按降序排列
*/
class MyIntComparator implements Comparator{
/**
* o1比o2大,返回-1;o1比o2小,返回1。
*/
public int compare(Object o1, Object o2) {
int i1 = ((Integer)o1).intValue();
int i2 = ((Integer)o2).intValue();
if (i1 < i2){
return 1;
}
if (i1 > i2){
return -1;
}
return 0;
}
}
评论
72 楼
jiage17
2009-08-14
我在东软某部门笔试真碰到了楼主说的这道题
71 楼
gordianyuan
2009-08-13
public class App { public static void main(String[] args) { try { sort("src/main/resources/intel.txt", "target/sun.txt"); } catch (IOException e) { e.printStackTrace(); } } private static void sort(String source, String target) throws IOException { Scanner scanner = new Scanner(new File(source)); List<App.Item> items = new ArrayList<App.Item>(); while (scanner.hasNextLine()) { String[] tokens = scanner.nextLine().split(" "); items.add(new App.Item(tokens[0], Integer.parseInt(tokens[1]))); } scanner.close(); Collections.sort(items, new Comparator<App.Item>() { @Override public int compare(Item o1, Item o2) { return o1.getNumber().compareTo(o2.getNumber()); } }); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter( target))); for (App.Item item : items) { writer.println(item.getName() + " " + item.getNumber()); } writer.close(); } static class Item { private String name; private Integer number; public Item(String name, Integer number) { this.name = name; this.number = number; } public String getName() { return name; } public Integer getNumber() { return number; } } }
70 楼
HelloJimmy
2009-08-13
Map<Integer, String> map = new TreeMap<Integer, String>(); while((temp = bfReader.readLine()) != null) { Integer t = getInteger(temp); if(map.containsKey(t)) { String value= map.get(t); temp += "\r\n" + value; } map.put(t, temp) ; }
上面是我的想法,可以解决TreeMap的key冲突问题
getInteger(temp);方法中我用的正则匹配。
69 楼
zhangyou1010
2009-08-13
把每行封装成一个对象,实现Comparable接口。
68 楼
fangwei
2009-08-12
<p>也来练练手</p>
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
try {
//读取
List<Person> persons = new ArrayList<Person>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("e:/test/intel.txt"),"GBK"));
String line = null;
while ((line = in.readLine()) != null) {
String[] temp = line.split(" ");
persons.add(new Person(Integer.valueOf(temp[1]),temp[0]));
}
in.close();
//排序
Collections.sort(persons, new Comparator<Person>(){
public int compare(Person o1, Person o2) {
return o1.getId().compareTo(o2.getId());
}
});
//写入
BufferedWriter out = new BufferedWriter(new FileWriter("e:/test/sun.txt"));
for (Person person : persons) {
String s = person.getName() + " " + person.getId();
System.out.println(s);
out.write(s+"\r\n");
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Person {
Integer id;
String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</pre>
<p> </p>
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
try {
//读取
List<Person> persons = new ArrayList<Person>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("e:/test/intel.txt"),"GBK"));
String line = null;
while ((line = in.readLine()) != null) {
String[] temp = line.split(" ");
persons.add(new Person(Integer.valueOf(temp[1]),temp[0]));
}
in.close();
//排序
Collections.sort(persons, new Comparator<Person>(){
public int compare(Person o1, Person o2) {
return o1.getId().compareTo(o2.getId());
}
});
//写入
BufferedWriter out = new BufferedWriter(new FileWriter("e:/test/sun.txt"));
for (Person person : persons) {
String s = person.getName() + " " + person.getId();
System.out.println(s);
out.write(s+"\r\n");
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Person {
Integer id;
String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</pre>
<p> </p>
67 楼
cloverprince
2009-01-20
sort -nk 2
66 楼
zozoh
2009-01-20
建立一个对象
public class Person{
String name;
int number;
Person(String line){
String[] ss = line.split(" ");
name = ss[0];
number = Integer.parseInt(ss[1]);
}
}
能让你的程序简单一些
public class Person{
String name;
int number;
Person(String line){
String[] ss = line.split(" ");
name = ss[0];
number = Integer.parseInt(ss[1]);
}
}
能让你的程序简单一些
65 楼
jiagyao
2009-01-15
nba520pz 写道
用String的split
没有用StringTokenizer好!
没有用StringTokenizer好!
恩,我不敢说 用String的split没有用StringTokenizer好,但是值得肯定的是他们都能实现不假。
我在百度摆了下,看了几篇相关文章感觉看后只是看到它们的些许不同,还是不能区别出来哪个好与坏。
还望牛牛们详细讲解下吧
64 楼
jiagyao
2009-01-15
MicroClimber 写道
你的程序写的很精彩,然而我们换一种角度,我们会发现您想多了。既然sort()是按key排序的,我们就可以让那些数字变成key嘛!!!!!!!!
/*TreeMap<Integer, String> map = new TreeMap<Integer, String>(
new MyIntComparator());*/ 改成 TreeMap map = new TreeMap();
我的输出是:(我注视了两句输出)
------------------读文件开始-------------------------------
以行为单位读取文件内容,每次读取一整行
line number is 1::小李 4564
line number is 2::小王 3234
line number is 3::阿斯顿 23444
line number is 4::小张 2342
line number is 5::小强 1030
line number is 6::小周 1020
------------------读文件结束-------------------------------
------------------写文件开始-------------------------------
写文件开始:E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt
key is :1020
vlaue is :小周
key is :1030
vlaue is :小强
key is :2342
vlaue is :小张
key is :3234
vlaue is :小王
key is :4564
vlaue is :小李
key is :23444
vlaue is :阿斯顿
写文件E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt成功!
---------------------------写文件结束--------------------------
/*TreeMap<Integer, String> map = new TreeMap<Integer, String>(
new MyIntComparator());*/ 改成 TreeMap map = new TreeMap();
我的输出是:(我注视了两句输出)
------------------读文件开始-------------------------------
以行为单位读取文件内容,每次读取一整行
line number is 1::小李 4564
line number is 2::小王 3234
line number is 3::阿斯顿 23444
line number is 4::小张 2342
line number is 5::小强 1030
line number is 6::小周 1020
------------------读文件结束-------------------------------
------------------写文件开始-------------------------------
写文件开始:E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt
key is :1020
vlaue is :小周
key is :1030
vlaue is :小强
key is :2342
vlaue is :小张
key is :3234
vlaue is :小王
key is :4564
vlaue is :小李
key is :23444
vlaue is :阿斯顿
写文件E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt成功!
---------------------------写文件结束--------------------------
呵呵 你看下所有回复贴吧,有两位写的很好很值得收藏,其中一位仁兄给了面向对象思想的程序段。
你说的要是就本题而言是对的,但是如果被读取文件包含数字重复字段就不适用了,我当时也是没注意到,
看来一些问题还是需要摆出来献丑的,经过高人的修正确实能学到许多
63 楼
MicroClimber
2009-01-15
你的程序写的很精彩,然而我们换一种角度,我们会发现您想多了。既然sort()是按key排序的,我们就可以让那些数字变成key嘛!!!!!!!!
/*TreeMap<Integer, String> map = new TreeMap<Integer, String>(
new MyIntComparator());*/ 改成 TreeMap map = new TreeMap();
我的输出是:(我注视了两句输出)
------------------读文件开始-------------------------------
以行为单位读取文件内容,每次读取一整行
line number is 1::小李 4564
line number is 2::小王 3234
line number is 3::阿斯顿 23444
line number is 4::小张 2342
line number is 5::小强 1030
line number is 6::小周 1020
------------------读文件结束-------------------------------
------------------写文件开始-------------------------------
写文件开始:E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt
key is :1020
vlaue is :小周
key is :1030
vlaue is :小强
key is :2342
vlaue is :小张
key is :3234
vlaue is :小王
key is :4564
vlaue is :小李
key is :23444
vlaue is :阿斯顿
写文件E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt成功!
---------------------------写文件结束--------------------------
/*TreeMap<Integer, String> map = new TreeMap<Integer, String>(
new MyIntComparator());*/ 改成 TreeMap map = new TreeMap();
我的输出是:(我注视了两句输出)
------------------读文件开始-------------------------------
以行为单位读取文件内容,每次读取一整行
line number is 1::小李 4564
line number is 2::小王 3234
line number is 3::阿斯顿 23444
line number is 4::小张 2342
line number is 5::小强 1030
line number is 6::小周 1020
------------------读文件结束-------------------------------
------------------写文件开始-------------------------------
写文件开始:E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt
key is :1020
vlaue is :小周
key is :1030
vlaue is :小强
key is :2342
vlaue is :小张
key is :3234
vlaue is :小王
key is :4564
vlaue is :小李
key is :23444
vlaue is :阿斯顿
写文件E:\Javapractice\2008-12-04-01\FirstJava\bin\FirstJava\test.txt成功!
---------------------------写文件结束--------------------------
62 楼
nba520pz
2009-01-14
用String的split
没有用StringTokenizer好!
没有用StringTokenizer好!
61 楼
tongyi121
2009-01-12
解决重复问题的groovy解法
def data = [] new File('d:/test.txt').eachLine{ def line = it.tokenize() data+=new Expando(key1:line[0],key2:line[1] as Integer) } def outFile = new File('d:/sun.txt') def printWriter = outFile.newPrintWriter() data.sort{it.key2}.each{ printWriter.println("${it.key1} ${it.key2}") } printWriter.flush() printWriter.close()
60 楼
E生迅徒
2009-01-12
boboism 写道
哎…… 这种还是保留在C语言的思想上。JavaSE 这么多的类库都不会用,用个arraylist包着hashmap不就得了。再匿名一个compararor接口不就得了。干嘛这么麻烦
大哥,你这个方法不就是前面那个嘛,hashmap不能解决重复key值的问题
59 楼
buddha17
2009-01-12
import java.io.*;
import java.util.*;
public class TestSort{
public static void main(String[] args){
String s="";
try{
FileReader file=new FileReader("test1.txt");
BufferedReader buff=new BufferedReader(file);
boolean eof=false;
while (!eof){
String line= buff.readLine();
if (line==null) eof =true;else {
s+=line;
System.out.println(line);
}
}
buff.close();
}catch (IOException e){e.printStackTrace();}
//s..split(" ");
System.out.println("ss=" + s );
StringTokenizer stoken = new StringTokenizer(s, " ");
String ss[]= new String[stoken.countTokens()];
int i=0;
// logger.info("**a.getArtkey()*******--nav pager-"+a.getArtkey());
while (stoken.hasMoreTokens()){
ss[i++]=stoken.nextToken();
}
String[] people=new String[ss.length/2];
int[] value=new int[ss.length/2];
int[] value2=new int[ss.length/2];
for( i=0;i<ss.length/2;i++){
System.out.println("i="+i+"pep= "+ ss[i*2]);
System.out.println("i="+i+"value = "+ ss[i*2+1]);
people[i]=ss[i*2];
value[i]=Integer.parseInt(ss[2*i+1]);
value2[i]=value[i];
}
Arrays.sort(value2);
try{
//FileWriter f=new FileWriter("test2.txt");
// BufferedWriter buff =new BufferedWriter(f);
FileOutputStream f=new FileOutputStream("test2.txt");
DataOutputStream buff=new DataOutputStream(f);
for( i=0;i<ss.length/2;i++){
int j=0;
while (value2[i]!=value[j]) j++;
System.out.println( "pep= "+ people[j]);
System.out.println( "value = "+ value2[i]);
buff. writeUTF( people[j] );
buff.writeUTF( String.valueOf(value2[i]));
}
buff.close();
}catch (IOException e){e.printStackTrace();
}}
}
上机调试通过.
import java.util.*;
public class TestSort{
public static void main(String[] args){
String s="";
try{
FileReader file=new FileReader("test1.txt");
BufferedReader buff=new BufferedReader(file);
boolean eof=false;
while (!eof){
String line= buff.readLine();
if (line==null) eof =true;else {
s+=line;
System.out.println(line);
}
}
buff.close();
}catch (IOException e){e.printStackTrace();}
//s..split(" ");
System.out.println("ss=" + s );
StringTokenizer stoken = new StringTokenizer(s, " ");
String ss[]= new String[stoken.countTokens()];
int i=0;
// logger.info("**a.getArtkey()*******--nav pager-"+a.getArtkey());
while (stoken.hasMoreTokens()){
ss[i++]=stoken.nextToken();
}
String[] people=new String[ss.length/2];
int[] value=new int[ss.length/2];
int[] value2=new int[ss.length/2];
for( i=0;i<ss.length/2;i++){
System.out.println("i="+i+"pep= "+ ss[i*2]);
System.out.println("i="+i+"value = "+ ss[i*2+1]);
people[i]=ss[i*2];
value[i]=Integer.parseInt(ss[2*i+1]);
value2[i]=value[i];
}
Arrays.sort(value2);
try{
//FileWriter f=new FileWriter("test2.txt");
// BufferedWriter buff =new BufferedWriter(f);
FileOutputStream f=new FileOutputStream("test2.txt");
DataOutputStream buff=new DataOutputStream(f);
for( i=0;i<ss.length/2;i++){
int j=0;
while (value2[i]!=value[j]) j++;
System.out.println( "pep= "+ people[j]);
System.out.println( "value = "+ value2[i]);
buff. writeUTF( people[j] );
buff.writeUTF( String.valueOf(value2[i]));
}
buff.close();
}catch (IOException e){e.printStackTrace();
}}
}
上机调试通过.
58 楼
zjq0717
2009-01-12
groovy的解法看着很爽啊
57 楼
xingqiliudehuanghun
2009-01-12
也写了一个,感觉读这种格式不严格数据应该用正则。第一次写这种程序,写web程序对文件读写部署,大家多指教
package com.saturday; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReadTxt { public static void main(String args[]){ try{ List lsRecords=readData("D:/Data.txt"); sortRecord(lsRecords,"asc"); writeData(lsRecords); }catch(FileNotFoundException ex){ System.out.println("无法读取数据文件!"); }catch(Exception ex){ System.out.println(ex.getMessage()); } } public static List readData(String sFilePath) throws Exception{ BufferedReader bufreader=null; List lsRecords=new ArrayList(); try{ StringBuffer sbData=new StringBuffer(); String sLineData=null; bufreader=new BufferedReader(new FileReader(sFilePath)); Pattern p=Pattern.compile( "^\\s*(.*?)\\s+(\\d+)\\s*$", Pattern.MULTILINE); while((sLineData=bufreader.readLine())!=null){ sbData.append(sLineData+"\n"); } Matcher m=p.matcher(sbData); while(m.find()){ lsRecords.add(m.group(1)+":"+m.group(2)); } }catch(Exception ex){ throw ex; }finally{ try{ if(bufreader!=null) bufreader.close(); }catch(Exception ex){} } return lsRecords; } public static void sortRecord(List lsRecords,String sSortSty){ Comparator AscCmp=new Comparator(){ public int compare(Object o1,Object o2){ String str1=(String)o1; String str2=(String)o2; int int1=Integer.parseInt( str1.substring(str1.indexOf(':')+1)); int int2=Integer.parseInt( str2.substring(str2.indexOf(':')+1)); return int1<int2?-1:1; } }; Comparator DesCmp=new Comparator(){ public int compare(Object o1,Object o2){ String str1=(String)o1; String str2=(String)o2; int int1=Integer.parseInt( str1.substring(str1.indexOf(':')+1)); int int2=Integer.parseInt( str2.substring(str2.indexOf(':')+1)); return int1<int2?1:-1; } }; if(sSortSty.equals("des")) Collections.sort(lsRecords,DesCmp); else Collections.sort(lsRecords,AscCmp); } public static void writeData(List lsRecords) throws Exception{ BufferedWriter bufwriter=null; try{ bufwriter=new BufferedWriter(new FileWriter("D:/SortedData.txt")); String sLineData=null; Iterator i=lsRecords.iterator(); while(i.hasNext()){ sLineData=(String)i.next(); sLineData=sLineData.replaceAll(":", " ")+"\n"; bufwriter.write(sLineData); } }catch(Exception ex){ throw ex; }finally{ try{ if(bufwriter!=null) bufwriter.close(); }catch(Exception ex){} } } }
56 楼
jiagyao
2009-01-12
呵呵,几天没上来,又多了十几条评论,谢谢大家的参与了,
感觉看帖子确实能学到不少东西,提高了~
感觉看帖子确实能学到不少东西,提高了~
55 楼
jltest
2009-01-10
没颜色看着头痛。。
import com.j2se.file.MyIntComparator;//自定义比较器 import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.TreeMap; /*** *读文件test.txt内容(文件内容格式: 小王【空格】10000【回车】 * 小强【空格】12345【回车】 *并对该文件内容按存款数排序,然后将其写入另一文件内 * *****/ public class fileSort { /***** * 以行为单位读写文件 *@param fileName 源文件 *@param toFileName 目标文件 * ****/ public static void read_writeFile(String fileName,String toFileName){ File file = new File(fileName); BufferedReader reader=null; TreeMap<Integer,String> map = new TreeMap<Integer,String>(new MyIntComparator()); File toFile = new File(toFileName); PrintWriter writer = null; try{ System.out.println("------------------读文件开始-------------------------------"); System.out.println(); System.out.println("以行为单位读取文件内容,每次读取一整行"); reader = new BufferedReader(new FileReader(file)); String tempString = null; String[] ss = null; int line = 1; //一次读一行,直到读取为null while((tempString = reader.readLine()) != null){ //显示行号 System.out.println("line number is "+line+"::"+tempString); line++; ss = tempString.split(" "); int i = 0; String value = ss[i]; int key =Integer.parseInt(ss[i+1]); System.out.println("key is:"+key); System.out.println("value is:"+value); map.put(key, value); } System.out.println("------------------读文件结束-------------------------------"); System.out.println(); System.out.println("------------------写文件开始-------------------------------"); System.out.println("写文件开始:"+file.getAbsolutePath()); writer = new PrintWriter(new FileOutputStream(toFile)); if(map !=null){ Object key = null; Object value = null; // 使用迭代器遍历Map的键,根据键取值 Iterator it = map.keySet().iterator(); while (it.hasNext()){ key = it.next(); value = map.get(key); System.out.println("key is :"+key); System.out.println("vlaue is :"+value); //能写各种基本类型数据 writer.print(value+" "); writer.print(key+" "); //换行 writer.println(); //写入文件 writer.flush(); } System.out.println("写文件"+file.getAbsolutePath()+"成功!"); System.out.println("---------------------------写文件结束--------------------------"); } }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try{ reader.close(); }catch(IOException e1){ e1.printStackTrace(); } } if(writer !=null){ writer.close(); } } } public static void main(String[] args){ String fileName = "D:/test.txt"; String toFileName = "D:/test1.txt"; fileSort.read_writeFile(fileName, toFileName); } } ----------------自定义比较器-------------------------------------- import java.util.Comparator; /** * 整数比较器,将整数按降序排列 */ class MyIntComparator implements Comparator{ /** * o1比o2大,返回-1;o1比o2小,返回1。 */ public int compare(Object o1, Object o2) { int i1 = ((Integer)o1).intValue(); int i2 = ((Integer)o2).intValue(); if (i1 < i2){ return 1; } if (i1 > i2){ return -1; } return 0; } }
54 楼
mfree
2009-01-10
spyker 写道
public class TestSort { public static void main(String[] args) { List<Integer> intList = new ArrayList<Integer>(); intList.add(123); intList.add(122223); intList.add(1233); intList.add(1234); intList.add(125); Integer[] intArr = intList.toArray(new Integer[intList.size()]); Arrays.sort(intArr); for (int i : intArr) { System.out.println(i); } } }
jdk1.5下面的一个sort
呵呵 熟悉下api
java.util.Collections.sort(intList);
53 楼
boboism
2009-01-10
哎…… 这种还是保留在C语言的思想上。JavaSE 这么多的类库都不会用,用个arraylist包着hashmap不就得了。再匿名一个compararor接口不就得了。干嘛这么麻烦
相关推荐
京东 校园招聘笔试试题--软件开发笔试题 -.docx京东 校园招聘笔试试题--软件开发笔试题 -.docx京东 校园招聘笔试试题--软件开发笔试题 -.docx京东 校园招聘笔试试题--软件开发笔试题 -.docx京东 校园招聘笔试试题--...
百度 2014校园招聘笔试试题--深度学习算法研发工程师.docx百度 2014校园招聘笔试试题--深度学习算法研发工程师.docx百度 2014校园招聘笔试试题--深度学习算法研发工程师.docx百度 2014校园招聘笔试试题--深度学习...
百度笔试题---数据库百度笔试题---数据库百度笔试题---数据库百度笔试题---数据库
C-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-公司招聘C笔试题.docxC-C-笔试题-...
CC++Java笔试题--很多大公司的面试和笔试题目-珍贵 CC++Java笔试题--很多大公司的面试和笔试题目-珍贵 CC++Java笔试题--很多大公司的面试和笔试题目-珍贵
北大青鸟Y2笔试题 --绝对内部题 9月Y2笔试 北大青鸟Y2笔试题 --绝对内部题 9月Y2笔试
各个公司面试笔试题 深圳-华为 武汉-高蓝德国际人 中兴笔试题 清华同方
海康2014-2015部分笔试题整理-技术支持.docx海康2014-2015部分笔试题整理-技术支持.docx海康2014-2015部分笔试题整理-技术支持.docx海康2014-2015部分笔试题整理-技术支持.docx海康2014-2015部分笔试题整理-技术支持...
(内部资料) 南京-安捷斯计算机.doc 南京-北极星.doc 南京-长天智远.doc ...没有全部列出,想要找工作的朋友不妨看一看,或许有些帮助,希望能让大家有所收获,也祝愿大家能早日找到理想的工作,别忘了多支持哦!
百度校园招聘笔试试题-深度学习算法研发工程师.docx百度校园招聘笔试试题-深度学习算法研发工程师.docx百度校园招聘笔试试题-深度学习算法研发工程师.docx百度校园招聘笔试试题-深度学习算法研发工程师.docx百度校园...
JAVA笔试题--Java选择题汇总.pdf
中国银行最全笔试资料历年笔试真题11-19年考试完整试题及答案解析+五大银行招聘考试练习题库(30多份pdf) 0-中国银行历年笔试真题11-18年 1-中国银行复习精华讲义 2-中国银行2019招聘考试完整试题及答案解析 3-五大...
高通笔试题--嵌入式C开发人员的最好的0x10道笔试题(详细解析).docx
常见LINUX笔试题---无私奉献了!希望对你们有帮助
硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附答案).docx硬件测试笔试题V1-(附...
【立信会计师事务所】面试笔试真题题-答案.pdf
2020校园招聘笔试测试题-答案.docx2020校园招聘笔试测试题-答案.docx2020校园招聘笔试测试题-答案.docx2020校园招聘笔试测试题-答案.docx2020校园招聘笔试测试题-答案.docx2020校园招聘笔试测试题-答案.docx2020校园...
(完整版)系统运维工程师笔试题目--答案版.pdf(完整版)系统运维工程师笔试题目--答案版.pdf(完整版)系统运维工程师笔试题目--答案版.pdf(完整版)系统运维工程师笔试题目--答案版.pdf(完整版)系统运维工程师笔试题目--...
高通笔试题--嵌入式C开发人员的最好的0x10道笔试题详细解析.docx
很不多的java笔试题 java面试笔试题---基础