1.程序读入a.dat文件和b.dat文件,最后生成cdat文件。2按部门名算出各部门的合计工资。3.文件各项目内容之间为tab分割。(如001 tab A tab 3000)4.文件内容如下,第一行为文件的项目名。5.部門code , 部門名的数据类型为String类型。 給料的数据类型为integer型(不超过6位)
a.bat部門code 部門名 給料 001 A 3000002 A 4000003 B 5000005 E 2000b.bat部門code 部門名 給料001 A 3000002 B 4000003 C 5500004 D 5000
下面是想要的C.bat
c.bat部門名 部門給料 A 10000B 9000C 5500D 5000E 2000F 8000麻烦诸位大侠给一下源码 谢谢了!
a.bat部門code 部門名 給料 001 A 3000002 A 4000003 B 5000005 E 2000b.bat部門code 部門名 給料001 A 3000002 B 4000003 C 5500004 D 5000
下面是想要的C.bat
c.bat部門名 部門給料 A 10000B 9000C 5500D 5000E 2000F 8000麻烦诸位大侠给一下源码 谢谢了!
import java.io.*;
import java.util.regex.*;
import java.util.*;;class Item {
int departNo;
String departName;
int salary; public Item(int departNo, String departName, int salary) {
super();
this.departNo = departNo;
this.departName = departName;
this.salary = salary;
}
}public class GenerateCDat {
public static void count(List items) {
for (int k = 0; k < items.size() - 1; k++) {
Item item = (Item) items.get(k);
for (int i = k + 1; i < items.size(); i++) {
if (((Item) items.get(i)).departName.equals(item.departName)) {
item.salary += ((Item) items.get(i)).salary;
items.remove(i);
i--;// 当移除元素后不需要i++即可访问下一个元素,所以使用i--抵消i++
}
}
}
} public static void main(String[] args) throws Exception {
Pattern pattern = Pattern.compile("(\\d+)\\s(\\w)\\s(\\d+)");
Matcher matcher = null;
List<Item> items = new ArrayList<Item>(); BufferedReader br = new BufferedReader(new FileReader("C:\\a.dat"));
String line = br.readLine();// 把文件指针移到第二行,忽略标题行
while ((line = br.readLine()) != null) {
matcher = pattern.matcher(line);
while (matcher.find()) {
items.add(new Item(Integer.valueOf(matcher.group(1)), matcher
.group(2), Integer.valueOf(matcher.group(3))));
}
} br = new BufferedReader(new FileReader("C:\\b.dat"));
line = br.readLine();// 把文件指针移到第二行,忽略标题行
while ((line = br.readLine()) != null) {
matcher = pattern.matcher(line);
while (matcher.find()) {
items.add(new Item(Integer.valueOf(matcher.group(1)), matcher
.group(2), Integer.valueOf(matcher.group(3))));
}
} count(items);//把部门名称相同的累加 BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\c.dat"));
bw.write("部門名 給料");
bw.newLine();
for (int i = 0; i < items.size(); i++) {
bw.write(((Item) items.get(i)).departName + " ");
bw.write(String.valueOf(((Item) items.get(i)).salary));
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}}
再添加一句br.close();
再添加一句br.close();
Stirng code;
Stirng name;
int geiliao;
get/set..
}
后来把他们放到一个list,把bat文件读进来再操作~
import java.io.*;public class Test {
public static void main(String[] args) {
String[] inFile = {"a.dat", "b.dat"};
String outFile = "c.dat";
Map<String, Integer> map = new TreeMap<String, Integer>();
String separator = System.getProperty("line.separator");
String buf;
try {
for (String file : inFile) {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((buf=br.readLine()) != null) {
if (buf.matches("^\\d+.*?\\d+$")) {
String[] sa = buf.split("\t");
if (map.containsKey(sa[1])) {
map.put(sa[1], map.get(sa[1])+Integer.valueOf(sa[2]).intValue());
} else {
map.put(sa[1], Integer.valueOf(sa[2]).intValue());
}
}
}
br.close();
}
PrintStream ps = new PrintStream(new FileOutputStream(outFile));
ps.println("部門名\t部門給料");
for (Map.Entry<String, Integer> e : map.entrySet()) {
ps.printf("%s\t%s%s", e.getKey(), e.getValue(), separator);
}
ps.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
谢谢一楼凌晨的热心帮助 代码很好很强大。。学习了~ 结贴啦
PS:那个F好像真是火星来的,复制多了一行。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;@SuppressWarnings("rawtypes")
public class FileRead { public static final String path_A = "D://workspace1/TEST/in/a.csv";
public static final String path_B = "D://workspace1/TEST/in/b.csv";
public static final String path_C = "D://workspace1/TEST/out/c.csv";
public static final String VALUE_TAB = "\t";
public static final String VALUE_NEWLINE = "\r";
private static final String ENCODING = "UTF-8"; /**
* @param args
*/
public static void main(String[] args) { Long start = System.currentTimeMillis(); FileRead fileRead = new FileRead();
fileRead.process(); Long end = System.currentTimeMillis();
Long s = end - start;
System.out.println(s);
} public void process() {
// Read A
List ioA = new ArrayList();
ioA = txtRead(path_A); // Set ListA to MapA from everyLine;
Map<String, Integer> mapA = new HashMap<String, Integer>();
mapA = txtLine(ioA); // Read B
List ioB = new ArrayList();
ioB = txtRead(path_B); // Set ListB to MapB from everyLine;
Map<String, Integer> mapB = new HashMap<String, Integer>();
mapB = txtLine(ioB); // File Merge And Sort
Map<String, Integer> mapC = new HashMap<String, Integer>();
mapC = fileMerge(mapA, mapB); // output File
outPutFile(mapC);
} private List txtRead(String inputFile) {
// 関数開始
String inputStr = "";
ArrayList<String> dataList = new ArrayList<String>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(inputFile));
inputStr = in.readLine();
while (inputStr != null) {
dataList.add(inputStr);
inputStr = in.readLine();
}
} catch (Exception e) {
} finally {
// System.out.println("Read File : " + inputFile);
try {
if (in != null) {
in.close();
in = null;
}
} catch (IOException e) {
}
}
// 関数終了
return dataList;
} private Map<String, Integer> txtLine(List inputList) {
Map<String, Integer> rntMap = new HashMap<String, Integer>();
String dataLine = "";
if (inputList != null && inputList.size() > 0) {
for (int i = 1; i < inputList.size(); i++) {
dataLine = (String) inputList.get(i);
String[] strArr = dataLine.split(VALUE_TAB, -1);
Integer count = Integer.valueOf(strArr[2]);
rntMap.put(strArr[1], count);
}
} return rntMap;
} private Map<String, Integer> fileMerge(Map<String, Integer> mapA,
Map<String, Integer> mapB) {
Set<String> set = mapA.keySet();
for (String key : set) {
// if B contains A,
// get Key from MapA and MapB
// A plus B = C;
// set total C to Map B;
if (mapB.containsKey(key)) {
Integer b = mapB.get(key);
Integer a = mapA.get(key);
Integer c = Integer.valueOf(b + a);
mapB.put(key, c);
} else {
mapB.put(key, mapA.get(key));
}
}
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
treeMap.putAll(mapB);
// System.out.println(treeMap);
return treeMap;
} private void outPutFile(Map<String, Integer> mapC) {
// 将文本写入字符输出流,缓冲各个字符,
// 从而提供单个字符、数组和字符串的高效写入。
BufferedWriter writer = null;
try {
// 文件和目录路径名的抽象表示形式。
File output = new File(path_C); // 文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(output); // OutputStreamWriter 是字符流通向字节流的桥梁:
// 可使用指定的 charset 将要写入流中的字符编码成字节。
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(
fileOutputStream, ENCODING); // 如果目录没有的话,创建目录。
File parent = output.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
writer = new BufferedWriter(outPutStreamWriter);
String txt = createTxtFile(mapC);
writer.write(txt);
} catch (Exception e) {
} finally {
try {
if (writer != null) {
// TXTをclose
writer.close();
writer = null;
}
} catch (IOException e) {
}
}
} private String createTxtFile(Map<String, Integer> mapC) {
String rntStr = "";
StringBuffer temp = new StringBuffer();
Set<String> set = mapC.keySet();
for (String key : set) {
temp.append(key);
temp.append(VALUE_TAB);
temp.append(mapC.get(key));
temp.append(VALUE_NEWLINE);
}
rntStr = temp.toString();
return rntStr;
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class Sample1 {
public static final String V_TAB = "\t";
public static final String V_ENTER = "\r\n";
public static final String MAX = "MAX";
public static final String OUT_FILE = "out/c.csv";
public static final String TITLE = "部門名 部門給料"; /**
* @param args
*/
public static void main(String[] args) {
// YANG
Long start = System.currentTimeMillis(); System.out.println("");
if (args.length == 0) {
System.out.println("パラメータが未指定");
return;
}
// Fileクラスをインスタンス化
File file1 = new File(args[0]);
File file2 = new File(args[1]);
new Sample1().check(file1, file2); try { // FileReaderクラスをインスタンス化
FileReader fr1 = new FileReader(file1);
FileReader fr2 = new FileReader(file2); // BufferedReaderクラスをインスタンス化
BufferedReader br1 = new BufferedReader(fr1);
BufferedReader br2 = new BufferedReader(fr2);
FileWriter fw = new FileWriter(OUT_FILE); String str1 = null;
String str2 = null;
int total = 0; // 1行目のタイトルを読み飛ばす
br1.readLine();
br2.readLine();
// c.datにタイトルを書き込む
fw.write(TITLE + V_ENTER);
//データ情報を読取
str1 = br1.readLine();
str2 = br2.readLine(); // ファイルを1行ずつ読み込む(2行目から)
while ((str1 != null) || (str2 != null)) {
if (MAX.equals(str1) && MAX.equals(str2)) {
break;
}
String[] st1 = str1.split(V_TAB);
String[] st2 = str2.split(V_TAB);
// 部門コードが同じ場合
if (st1[0].compareTo(st2[0]) == 0) {
// 同じ部門コードの給料を合計
total = Integer.parseInt(st1[2]) + Integer.parseInt(st2[2]);
fw.write(st1[1].concat(V_TAB + total + V_ENTER));
// a.datとb.datファイルの次行を読取
str1 = br1.readLine();
str2 = br2.readLine();
// a.datの部門コード > b.datの部門コード 場合
} else if (st1[0].compareTo(st2[0]) > 0) {
// b.datの内容を書き込む
fw.write(st2[1].concat(V_TAB + st2[2] + V_ENTER));
// b.datファイルの次行を読取
str2 = br2.readLine();
// a.datの部門コード < b.datの部門コード 場合
} else if (st1[0].compareTo(st2[0]) < 0) {
// a.datの内容を書き込む
fw.write(st1[1].concat(V_TAB + st1[2]) + V_ENTER);
// a.datファイルの次行を読取
str1 = br1.readLine(); }
if (str1 == null) {
str1 = MAX;
}
if (str2 == null) {
str2 = MAX;
}
}
// ファイルを閉じる
br1.close();
br2.close();
fw.close(); } catch (FileNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
Long end = System.currentTimeMillis();
Long s = end-start;
System.out.println(s);
} public void check(File file1, File file2) { // ファイルが存在するかどうかを判定
if (!file1.exists() || !file2.exists()) {
// ファイルが存在しない場合は処理終了
System.out.println("ファイルが存在しない");
return;
} // 指定されたパスがファイルかどうかを判定
if (!file1.isFile() || !file2.isFile()) {
// ディレクトリを指定した場合は処理終了
System.out.println("ファイル以外を指定");
return;
} // ファイルが読み込み可能かどうかを判定
if (!file1.canRead() || !file2.canRead()) {
// ファイルが読み込み不可の場合は処理終了
System.out.println("ファイルが読み込み不可");
return;
} }
}
第一种算法处理2个文件各5万行,用时1秒。
第一种算法处理2个文件各5万行,用时0.5秒。
但是第一个方法按部门排序了,第二个没有,只是并行处理。
上面有个仁兄也用TREEMAP的那位,用时是3秒,我不知道是慢在哪里,有谁帮分析下么?