[英]Convert file to byte array and vice versa
我发现了许多将文件转换为字节数组并将字节数组写入存储文件的方法。
我想要的是将java.io.File
转换为字节数组,然后将字节数组转换回java.io.File
。
我不想像下面这样将它写到存储中:
//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
我想以某种方式执行以下操作:
File myFile = ConvertfromByteArray(bytes);
否则试试这个:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Temp {
public static void main(String[] args) {
File file = new File("c:/EventItemBroker.java");
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
}
}
public class WriteByteArrayToFile {
public static void main(String[] args) {
String strFilePath = "Your path";
try {
FileOutputStream fos = new FileOutputStream(strFilePath);
String strContent = "Write File using Java ";
fos.write(strContent.getBytes());
fos.close();
}
catch(FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
}
我认为您误解了java.io.File
类的真正含义。 它只是系统上文件的表示,即它的名称、路径等。
您甚至查看过java.io.File
类的 Javadoc 吗? 看看这里如果您检查它具有的字段或方法或构造函数参数,您会立即得到提示,即所有内容都是 URL/路径的表示。
Oracle 在他们的Java File I/O 教程中提供了相当丰富的教程,也提供了最新的 NIO.2 功能。
使用 NIO.2,您可以使用java.nio.file.Files.readAllBytes()在一行中读取它。
同样,您可以使用java.nio.file.Files.write()将所有字节写入字节数组。
更新
由于问题被标记为 Android,更传统的方法是将FileInputStream
包装在BufferedInputStream
,然后将其包装在ByteArrayInputStream
。 这将允许您读取byte[]
的内容。 类似地,对于OutputStream
存在它们的对应物。
你不能这样做。 File
只是引用文件系统中文件的一种抽象方式。 它不包含任何文件内容本身。
如果您尝试创建可以使用File
对象引用的内存中文件,您也无法做到这一点,如this thread 、 this thread和许多其他地方所述。 .
Apache FileUtil 提供了非常方便的方法来进行转换
try {
File file = new File(imagefilePath);
byte[] byteArray = new byte[file.length()]();
byteArray = FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
没有这样的功能,但您可以通过File.createTempFile()使用临时文件。
File temp = File.createTempFile(prefix, suffix);
// tell system to delete it when vm terminates.
temp.deleteOnExit();
您不能为 File 执行此操作,它主要是一个智能文件路径。 你能重构你的代码,以便它声明变量,并传递参数,类型为 OutputStream 而不是 FileOutputStream? 如果是这样,请参阅类java.io.ByteArrayOutputStream和java.io.ByteArrayInputStream
OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...
1-传统方式
传统的转换方式是使用 InputStream 的 read() 方法如下:
public static byte[] convertUsingTraditionalWay(File file)
{
byte[] fileBytes = new byte[(int) file.length()];
try(FileInputStream inputStream = new FileInputStream(file))
{
inputStream.read(fileBytes);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
2-Java 蔚来
使用 Java 7,您可以使用 nio 包的 Files 实用程序类进行转换:
public static byte[] convertUsingJavaNIO(File file)
{
byte[] fileBytes = null;
try
{
fileBytes = Files.readAllBytes(file.toPath());
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
3- Apache Commons IO
除了JDK,您还可以通过两种方式使用Apache Commons IO库进行转换:
3.1. IOUtils.toByteArray()
public static byte[] convertUsingIOUtils(File file)
{
byte[] fileBytes = null;
try(FileInputStream inputStream = new FileInputStream(file))
{
fileBytes = IOUtils.toByteArray(inputStream);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
3.2. FileUtils.readFileToByteArray()
public static byte[] convertUsingFileUtils(File file)
{
byte[] fileBytes = null;
try
{
fileBytes = FileUtils.readFileToByteArray(file);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return fileBytes;
}
@RequestMapping("/download")
public byte[] download() throws Exception {
File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
byte[] byteArray = new byte[(int) f.length()];
byteArray = FileUtils.readFileToByteArray(f);
return byteArray;
}
private ResponseEntity<byte[]> getDownload(){
URI end = URI.create(your url which server has exposed i.e. bla
bla/download);
return rest.getForEntity(end,byte[].class);
}
public static void main(String[] args) throws Exception {
byte[] byteArray = new TestClient().getDownload().getBody();
FileOutputStream fos = new
FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");
fos.write(byteArray);
fos.close();
System.out.println("file written successfully..");
}
//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4");
FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);
//Now the bytes of the file are contain in the "byte[] data"
/*If you want to convert these bytes into a file, you have to write these bytes to a
certain location, then it will make a new file at that location if same named file is
not available at that location*/
FileOutputStream fileOutputStream =new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Video.mp4");
fileOutputStream.write(data);
/* It will write or make a new file named Video.mp4 in the "Download" directory of
the External Storage */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.