这种情况java.io, nio没有大区别
byte[] buf = new byte[8 * 1024]try (OutputStream out = new new FileOutputStream(outfile)) {
for (File f : txtFiles) {
好拿 try (FileInputStream in = new FileInputStream(f)) {
org.apache.commons.io.IOUtils.copyLarge(in, out, buf)
核纳 }
}
}
要是linux下,shell里直接执行cat *.txt >友氏搭out.txt就可以,不用写代码
使用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"})
}
}
java可以使用FileChannel快速高效地将多个文件合并到一起,以下戚穗是详细代码:
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) {}
}
}
public static void main(String[] args) {
mergeFiles("D:/output.txt", new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"})
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)