我发现了许多将文件转换为字节数组并将字节数组写入存储文件的方法.
我想要的是转换java.io.File
为字节数组,然后将字节数组转换回a java.io.File
.
我不想把它写成存储,如下所示:
//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
Run Code Online (Sandbox Code Playgroud)
我想以某种方式做以下事情:
File myFile = ConvertfromByteArray(bytes);
Run Code Online (Sandbox Code Playgroud)
Raj*_*mar 54
否则试试这个:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
jbx*_*jbx 22
我想你误解了这个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()来写入字节数组中的所有字节.
UPDATE
由于这个问题被标记的Android,更传统的方式是包裹FileInputStream
在一个BufferedInputStream
,然后包裹在一个ByteArrayInputStream
.这将允许您阅读一个内容byte[]
.同样地,它们的对应物也存在OutputStream
.
Apache FileUtil提供了非常方便的方法来进行转换
try {
File file = new File(imagefilePath);
byte[] byteArray = new byte[file.length()]();
byteArray = FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
168388 次 |
最近记录: |