使用java编程语言,对文件进行 *** 作,合并多个文件,代码如下:
import static java.lang.System.outimport java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.Arrays
public class test {
public static final int BUFSIZE = 1024 * 8
public static void mergeFiles(String outFile, String[] files) {
FileChannel outChannel = null
out.println("Merge " + Arrays.toString(files) + " into " + outFile)
try {
outChannel = new FileOutputStream(outFile).getChannel()
for(String f : files){
FileChannel fc = new FileInputStream(f).getChannel()
ByteBuffer bb = ByteBuffer.allocate(BUFSIZE)
while(fc.read(bb) != -1){
bb.flip()
outChannel.write(bb)
bb.clear()
}
fc.close()
}
out.println("Merged!! ")
} catch (IOException ioe) {
ioe.printStackTrace()
} finally {
try {if (outChannel != null) {outChannel.close()}} catch (IOException ignore) {}
}
}
//下面代码是将D盘的1.txt 2.txt 3.txt文件合并成out.txt文件。
public static void main(String[] args) {
mergeFiles("D:/output.txt", new String[]{"D:/1.txt", "D:/2.txt", "D:/3.txt"})
}
}
代码不写了,思路:首先读取文件,依次读取所有目录,然后递归子目录,将所有目录下以a|b名称开头的文件内容分别按照行读取到a|b的ArrayList中,循环所有的ArrayList ,将每个内容都put到HashSet中去,这样,就得到你要的结果,最终输出到c目录下
当然,可以不读取到ArrayList中,直接put到HashSet,不过这样的话,就无法查找每个文件的原始内容。建议先分文件读取到多个ArrayList ,但不影响你的程序结果(可能会影响最终内容的顺序)
import java.io.BufferedReaderimport java.io.FileReader
import java.io.FileWriter
import java.io.IOException
public class Read {
String file1Path = "D:/First.txt"
String file2Path = "D:/Last.txt"
String resultPath = "D:/Result.txt"
public static void main(String[] args) throws IOException{
Read r = new Read()
r.readFile()
}
public void readFile() throws IOException{
BufferedReader in1 = new BufferedReader(new FileReader(file1Path))
BufferedReader in2 = new BufferedReader(new FileReader(file2Path))
String line1 = null, line2 = null
String s1 = "", s2 = "", s3 = ""
int length
char a,b
FileWriter fw = null
fw = new FileWriter(resultPath,false)
boolean flag = true
while(flag){
line1 = in1.readLine()
line2 = in2.readLine()
//当First.txt和Last.txt行数不同时
if(line1 == null &&line2 != null){
s2 += line2
flag = false
continue
}
if(line2 == null &&line1 != null){
s3 += line1
flag = false
continue
}
if(line1 == null &&line2 == null){
flag = false
continue
}
length = (line1.length() <line2.length())?line1.length():line2.length()
for(int i = 0i <lengthi ++){
a = line1.charAt(i)
b = line2.charAt(i)
if(a == b){
s1 += a
}else if(a != b){
s2 += a
s3 += b
}
}
//当一行字符串长度不同时
if(line1.length() >line2.length()){
s2 += line1.substring(line2.length(), line1.length())
}else if(line1.length() <line2.length()){
s3 += line2.substring(line1.length(), line2.length())
}
}
fw.write(s1 + "\r\n来自文件一:" + s2 + "\r\n来自文件二:" + s3)
fw.close()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)