这就是刚刚那篇文章中所遇到的问题 找到了两种比较好的解决办法 这里记录一下
合并多个文件
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
public static final int BUFSIZE = 1024 * 8;
/**
* 合并多个文件
* @param outFile 输出文件路径
* @param files 要合并的文件路径名数组
*/
public static void mergeFiles(String outFile, String[] files) {
FileChannel outChannel = null;
try {
outChannel = new FileOutputStream(outFile).getChannel();
for(String f : files){
Charset charset=Charset.forName("UTF-8");
CharsetDecoder chdecoder=charset.newDecoder();
CharsetEncoder chencoder=charset.newEncoder();
FileChannel fc = new FileInputStream(f).getChannel();
ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
CharBuffer charBuffer=chdecoder.decode(bb);
ByteBuffer nbuBuffer=chencoder.encode(charBuffer);
while(fc.read(nbuBuffer) != -1){
bb.flip();
nbuBuffer.flip();
outChannel.write(nbuBuffer);
bb.clear();
nbuBuffer.clear();
}
fc.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (outChannel != null) {
outChannel.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
合并两个文件
/**
* 合并两个文件
* @param file1
* @param file2
* @param targetFile
*/
public static void merge(String file1,String file2,String targetFile) {
SequenceInputStream sis = null;
BufferedOutputStream bos = null;
try {
InputStream s1 = new FileInputStream(file1);
InputStream s2 = new FileInputStream(file2);
// 数据源
sis = new SequenceInputStream(s1, s2);
// 目的地
bos = new BufferedOutputStream(
new FileOutputStream(targetFile));
// 读写
byte[] bys = new byte[1024];
int len = 0;
while ((len = sis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bos.close();
sis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
还有一个替换文本中所有字符的方法 也记一下
/**
*
* @param fileName 文件名
* @param srcStr 需要被替换的文字
* @param replaceStr 替换的文字
*/
public static void replaceAllToTxt(String fileName ,String srcStr,String replaceStr) {
File file = null;
BufferedReader bufIn = null;
CharArrayWriter tempStream = null;
FileWriter out = null;
try {
// 读
file = new File(fileName);
FileReader in = new FileReader(file);
bufIn = new BufferedReader(in);
// 内存流, 作为临时流
tempStream = new CharArrayWriter();
// 替换
String line = null;
while ( (line = bufIn.readLine()) != null) {
// 替换每行中, 符合条件的字符串
line = line.replaceAll(srcStr, replaceStr);
// 将该行写入内存
tempStream.write(line);
// 添加换行符
tempStream.append(System.getProperty("line.separator"));
}
// 将内存中的流 写入 文件
out = new FileWriter(file);
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭 输入流
try {
bufIn.close();
tempStream.writeTo(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}