【问题标题】:Regarding four byte array needs to be write to a new File关于四字节数组需要写入一个新文件
【发布时间】:2019-07-26 07:14:16
【问题描述】:
List<byte[]> A has four byte[] values

当我为数组 A 运行 for each 循环并使用 writeByteArrayToFile(File,byte[],true); 写入文件时;

只是覆盖,最后一个byte[]值只写入文件?

我需要写所有字节[]???

【问题讨论】:

标签: java


【解决方案1】:

解决方案:

public static void main(String[] args) throws IOException {
        File A = new File("A");
        File B = new File("B");
        File C = new File("C");
        File D = new File("D");

        File E = new File("E");
        mergeFiles(E, A, B, C, D);
}

static void mergeFiles(File destination, File... files) throws IOException {
    byte[] buffer = new byte[512];
    int count;
    try (FileOutputStream fos = new FileOutputStream(destination)) {
        for (File file : files) {
            try (FileInputStream fis = new FileInputStream(file)) {
                while ((count = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, count);
                }
            }
        }
    }
}

【讨论】:

  • Anton 我几乎明白了,非常感谢@Anton,但我有一个问题,当文件 A 进入时,第一次 while 循环变得错误..只有三个文件 B、C、D 得到写..你能找到问题吗???
  • @SethuRamalingam 方法 read() 返回读入缓冲区的总字节数,如果由于已到达文件末尾而没有更多数据,则返回 -1。
  • 谢谢你..但是我已经尝试了第四个文件 D 只写在文件 E 中..但是我需要所有四个文件..请帮我先生..
  • write 方法在每次迭代期间覆盖 for 循环,因此只有最后一个文件被写入文件 E???
  • 文件 A 中写入了值 文件 B 中写入了值 文件 C 中写入了值 文件 D 中写入了值 File E = new File(“E”); E = 合并文件(E、A、B、C、D); Private File mergeFiles(File E,File... files) throws IOException{ byte[] buffer = new byte[300000];整数计数; try(FileOutputStream fileOutputStream = new FileOutputStream(E)){ for(File file : files){ try(FileInputStream fileInputStream = new FileInputStream(file)){ while((count=fileInputStream.read(buffer)) != -1){ fileOutputStream.write(buffer,0,count); } } } } 返回 E; }
猜你喜欢
  • 2012-07-11
  • 2014-04-10
  • 2016-12-13
  • 1970-01-01
  • 2021-07-19
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多