修复和优化后的代码如下:

package main

import (
	"bytes"
	"encoding/binary"
	"io/ioutil"
	"os"
)

// fixFiles2 合并文件2
func fixFiles2(fileList []string, fileOutPath string) {
	// 先进行获取文件长度 和音频文件长度 写入到Head byte数组中!
	var totalLength int64
	length := make([]int64, len(fileList))
	for i, file := range fileList {
		info, err := os.Stat(file)
		if err != nil {
			panic(err)
		}
		length[i] = info.Size() - 44
		totalLength += length[i]
	}

	// 设置总长度
	fileLength := make([]byte, 4)
	binary.BigEndian.PutUint32(fileLength, uint32(totalLength+36))

	dataLength := make([]byte, 4)
	binary.BigEndian.PutUint32(dataLength, uint32(totalLength))

	// 数组反转
	fileLength = reverseBytes(fileLength)
	dataLength = reverseBytes(dataLength)

	head := make([]byte, 44)

	// 进行获取头部信息
	for i, file := range fileList {
		fileBytes, err := ioutil.ReadFile(file)
		if err != nil {
			panic(err)
		}

		if i == 0 {
			copy(head, fileBytes[:44])
			copy(head[4:8], fileLength)
			copy(head[40:44], dataLength)
		}

		// 先将头文件写进去!
		head = append(head, fileBytes[44:]...)
	}

	// 进行写出文件
	err := ioutil.WriteFile(fileOutPath, head, 0644)
	if err != nil {
		panic(err)
	}
}

// reverseBytes 数组反转
func reverseBytes(arr []byte) []byte {
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		arr[i], arr[j] = arr[j], arr[i]
	}
	return arr
}

修复和优化的主要改动如下:

  1. 将头部信息的写入操作从byteArrayOutputStream改为直接操作head字节数组。这样避免了使用bytes.NewBufferWrite方法,提高了效率。
  2. 将每个文件的数据直接追加到head字节数组中,避免了使用bytes.NewBufferWrite方法,提高了效率。
  3. 使用append函数将head字节数组写入文件,避免了使用ioutil.WriteFile方法时的拷贝操作,提高了效率
请修复优化下面代码:package mainimport 	bytes	encodingbinary	ioioutil	os fixFiles2 合并文件2func fixFiles2fileList string fileOutPath string 	 先进行获取文件长度 和音频文件长度 写入到Head byte数组中!	var totalLength int64	length = makei

原文地址: http://www.cveoy.top/t/topic/h3BH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录