Skip to content

Latest commit

 

History

History
86 lines (56 loc) · 2.44 KB

File metadata and controls

86 lines (56 loc) · 2.44 KB

Java 程序:将文件转换为字节数组,反之亦然

原文: https://www.programiz.com/java-programming/examples/convert-file-byte-array

在此程序中,您将学习如何在 Java 中将File对象转换为byte[],反之亦然。

在将文件转换为字节数组之前,反之亦然,我们假设在src文件夹中有一个名为test.txt的文件。

这是test.txt的内容

This is a
Test file.

示例 1:将文件转换为byte[]

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileByte {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";

        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            System.out.println(Arrays.toString(encoded));
        } catch (IOException e) {

        }
    }
}

运行该程序时,输出为:

[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

在上面的程序中,我们将文件的路径存储在变量path中。

然后,在try块内部,我们使用readAllBytes()方法从给定的path读取所有字节。

然后,我们使用ArraystoString()方法来打印字节数组。

由于readAllBytes()可能会抛出IOException,因此我们在程序中使用了try-catch块。


示例 2:将byte[]转换为文件

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ByteFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String finalPath = System.getProperty("user.dir") + "\\src\\final.txt";

        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            Files.write(Paths.get(finalPath), encoded);
        } catch (IOException e) {

        }
    }
} 

运行程序时,test.txt的内容将复制到final.txt中。

在上面的程序中,我们使用了与示例 1 相同的方法从存储在path中的File中读取所有字节。 这些字节存储在encoded数组中。

我们还有一个finalPath,其中要写入字节。

然后,我们仅使用Fileswrite()方法将编码的字节数组写入给定finalPath中的文件中。