很简单撒。利用HashMap不能重复的特点就可以了。
你先读b.txt的数据到HashMap.
然后再读a.txt 到同一个Map
这个时候如果遇到重复的Key,value就会被覆盖的。
就达到你的要求了撒。
参考代码:
将A.txt B.txt 换成你自己的路劲就可以了。
package aimport java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.HashMap
import java.util.Iterator
import java.util.Map
import java.util.Map.Entry
public class TestReturn {
private static HashMap<String, String> map=new HashMap<String, String>()
public static void getTxt(File file){
try {
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file))
BufferedReader bufferedReader = new BufferedReader(read)
String lineTxt = null
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt)
map.put(lineTxt.split(",")[0], lineTxt.split(",")[1])
}
read.close()
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace()
}
}
public static void writeTxt(File file) throws IOException
{
if(!file.exists())
file.createNewFile()
FileOutputStream outputStream = new FileOutputStream(file)
FileChannel channel = outputStream.getChannel()
String content=""
Iterator iter = map.entrySet().iterator()
while(iter.hasNext()){
Map.Entry<String, String> entry= (Entry<String, String>) iter.next()
content+=entry.getKey()+","
content+=entry.getValue()+"\n"
}
ByteBuffer buffer = ByteBuffer.allocate(content.getBytes().length)
buffer.put(content.getBytes())
buffer.flip() //此处必须要调用buffer的flip方法
channel.write(buffer)
channel.close()
outputStream.close()
}
public static void main(String[] args) throws IOException {
//处理文件B
getTxt(new File("d://B.txt"))
//处理文件A
getTxt(new File("d://A.txt"))
//数写入C
writeTxt(new File("d://C.txt"))
}
}
可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。BufferedReader bre = null
try {
String file = "D:/test/test.txt"
bre = new BufferedReader(new FileReader(file))//此时获取到的bre就是整个文件的缓存流
while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
{
System.out.println(str)//原样输出读到的内容
};
备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。