十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
使用java编程语言,对文件进行操作,合并多个文件,代码如下:
创新互联建站-专业网站定制、快速模板网站建设、高性价比犍为网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式犍为网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖犍为地区。费用合理售后完善,10余年实体公司更值得信赖。
import static java.lang.System.out;
import 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"});
}
}
java可以使用FileChannel快速高效地将多个文件合并到一起,以下是详细代码:
import static java.lang.System.out;
import 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) {}
}
}
public static void main(String[] args) {
mergeFiles("D:/output.txt", new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"});
}
}
两个类放到包里面后,选择一个类设为启动类或者再写一个启动类,然后在启动类里面调用其它类就好了