1. 使用`Files.readAllBytes()`方法:
import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;Path path = Paths.get("C:/temp/test.txt");byte[] data = Files.readAllBytes(path);
2. 使用`FileInputStream`和`ByteArrayOutputStream`:
import java.io.File;import java.io.FileInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;File file = new File("C:/temp/test.txt");byte[] bytes = new byte[(int) file.length()];try (FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream bos = new ByteArrayOutputStream()) {int buf_size = 1024;byte[] buffer = new byte[buf_size];int len;while ((len = fis.read(buffer, 0, buf_size)) != -1) {bos.write(buffer, 0, len);}bytes = bos.toByteArray();} catch (IOException e) {e.printStackTrace();}

3. 使用`FileChannel`和`MappedByteBuffer`:
import java.io.File;import java.io.RandomAccessFile;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;File file = new File("C:/temp/test.txt");try (RandomAccessFile raf = new RandomAccessFile(file, "r");FileChannel channel = raf.getChannel()) {long fileSize = channel.size();if (fileSize > Integer.MAX_VALUE) {System.out.println("File too big...");return null;}MappedByteBuffer buffer = channel.map(MapMode.READ_ONLY, 0, (int) fileSize);byte[] bytes = new byte[(int) fileSize];buffer.get(bytes);return bytes;} catch (IOException e) {e.printStackTrace();}
4. 使用`Apache Commons IO`库:
import org.apache.commons.io.FileUtils;byte[] fileBytes = FileUtils.readFileToByteArray(new File("C:/temp/test.txt"));
请根据您的具体需求选择合适的方法。需要注意的是,`Files.readAllBytes()`方法会将整个文件读入内存,因此对于大文件可能会导致`OutOfMemoryError`。如果文件非常大,建议使用流式读取方法,如`FileInputStream`和`FileChannel`。
