English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Grund教程

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Java Ausnahmebehandlung

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将文件对象(File)与字节数组(byte[])相互转换

Java Beispiele大全

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

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

这是test.txt的内容

This is a
Test file.

示例1:将File转换为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()方法从给定的路径中读取所有字节。

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

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

示例2:byte []转换为File

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) {
        }
    }
}

Beim Ausführen des Programmstest.txtDer Inhalt wird infinal.txt.

Im obigen Programm verwenden wir denselben Ansatz wie im Beispiel1Der gleiche Ansatz liest alle Bytes aus dem im path gespeicherten File aus. Diese Bytes werden im Array encoded gespeichert.

Wir haben auch einen finalPath, um Bytes hineinzuschreiben

Dann verwenden wir nur die Methode write() von Files, um den codierten Byte-Array in die Datei am gegebenen finalPath einzuschreiben.

Java Beispiele大全