字节[]到Java中的文件
使用Java: 我有一个表示文件的字节[]到Java中的文件,java,arrays,file,io,inputstream,Java,Arrays,File,Io,Inputstream,使用Java: 我有一个表示文件的字节[] 如何将其写入文件(即C:\myfile.pdf) 我知道它是用InputStream完成的,但我似乎无法解决它。使用 或者,如果你坚持为自己工作 try (FileOutputStream fos = new FileOutputStream("pathname")) { fos.write(myByteArray); //fos.close(); There is no more need for this line since you
字节[]
如何将其写入文件(即C:\myfile.pdf
)
我知道它是用InputStream完成的,但我似乎无法解决它。使用
或者,如果你坚持为自己工作
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
尝试
OutputStream
或更具体地说FileOutputStream
我知道这是用InputStream完成的
实际上,您将看到一个…基本示例:
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
FileOutputStream fs = new FileOutputStream(new File(fileName));
bs = new BufferedOutputStream(fs);
bs.write(byte_array);
bs.close();
bs = null;
} catch (Exception e) {
e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
没有任何图书馆:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
与:
与:
所有这些策略都要求您在某个时刻捕获IOException 从Java7开始,您可以使用try with resources语句来避免资源泄漏,并使代码更易于阅读。更多关于这个 要将
byteArray
写入文件,请执行以下操作:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
另一个使用
java.nio.file
的解决方案:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
同样从Java 7开始,一行Java.nio.file.Files:
Files.write(new File(filePath).toPath(), data);
其中数据是字节[],文件路径是字符串。您还可以使用StandardOpenOptions类添加多个文件打开选项。使用try/catch添加抛出或环绕。这是一个程序,我们使用字符串生成器读取和打印字节偏移量和长度数组,并将字节偏移量长度数组写入新文件 `在此处输入代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//
public class ReadandWriteAByte {
public void readandWriteBytesToFile(){
File file = new File("count.char"); //(abcdefghijk)
File bfile = new File("bytefile.txt");//(New File)
byte[] b;
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream (file);
fos = new FileOutputStream (bfile);
b = new byte [1024];
int i;
StringBuilder sb = new StringBuilder();
while ((i = fis.read(b))!=-1){
sb.append(new String(b,5,5));
fos.write(b, 2, 5);
}
System.out.println(sb.toString());
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null);
fis.close(); //This helps to close the stream
}catch (IOException e){
e.printStackTrace();
}
}
}
public static void main (String args[]){
ReadandWriteAByte rb = new ReadandWriteAByte();
rb.readandWriteBytesToFile();
}
}
控制台中的O/p:fghij
新文件中的O/p:cdefg//将文件转换为字节[]///////////////////
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
///////////////////////2]字节[]到文件///////////////////////////
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
您可以尝试:
更多详细信息:@R.Bemrose好吧,它可能在sad情况下成功地清理了资源。从文档:注意:从v1.3开始,如果文件的父目录不存在,则将创建它们。如果写入失败,您将泄漏输出流。您应该始终使用
try{}finally{}
来确保正确的资源清理。fos.close()语句是多余的,因为您正在使用try with resources自动关闭流,即使写入失败。为什么我要使用apache commons IO,当它是两行常规Java时,您可以使用path.get(filePath)
而不是新文件(filePath).toPath()
@Halil我认为这不对。根据javadocs,open options有一个可选的第三个参数,“如果没有选项,那么这个方法的工作原理就好像CREATE、TRUNCATE_EXISTING和WRITE选项存在一样。换句话说,它打开文件进行写入,如果文件不存在则创建文件,或者最初将现有的常规文件截断为0大小。”谢谢你的回答。但是我对“文件名”有点困惑,我的意思是你保存数据的文件类型是什么?您能解释一下吗?您好,SRam,这完全取决于您的应用程序为什么要进行转换以及您希望输出的格式,我建议您选择.txt格式(例如:-myconvertedfilename.txt),但这也是您的选择。我尝试过使用它,但它会导致非UTF-8字符的字节出现问题,因此,如果您试图编写单个字节来构建一个文件,我会小心处理这个问题。我认为C:\myfile.pdf
无论如何都不能在Android上工作…;)@TB这种情况下的字符集如何?字符集似乎不相关,因为我们在写字节,而不是字符。你说的是真的,我理解我的错误。这种情况下的字符集如何?@pavan charset ofpath
?FileOutputStream文档没有提到这一点,因此这可能是特定于平台的。我猜在绝大多数情况下都是UTF-8<代码>字节按原样写入,不涉及字符集。
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
new LengthOf(new TeeInput(array, new File("a.txt"))).value();