yangbobo1992 2013-07-23 10:56
浏览 314
已采纳

java 读取各种类型文件的二进制并且写入到这些类型的文件,内容等等都不变。

问题:如题!!!!!

我现在是用java读取了txt、word、execl三种类型的文件。并且得到他们的二进制流(也就是byte数组)。
我要怎么通过这个byte数组写入到这些类型的文件中(注:内容不变、文件类型不变、总之所有的东西都不变,还是原来一模一样的东西)。

请问我应该怎么实现呢?

读取文件代码,并且得到byte[].
[code="java"]public byte[] readFile(String filename){
// System.out.println("read file " + filename);
try{

if(filename==null || filename.equals(""))
{
System.out.println("filename is invalid.filename=" + filename);
return new byte[0];
}
File file =new File(filename);
long len = file.length();
byte[] bytes = new byte[(int)len];
try{
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read( bytes );
if (r != len)
throw new IOException("读取文件不正确");
bufferedInputStream.close();
}catch(Exception ex){
ex.printStackTrace();
System.out.println("Read file Exception,filename=" + filename+"---"+ex);
}

return bytes;
}catch(Exception ex){
System.out.println("Read file Exception,filename=" + filename+"---"+ex);
}
return new byte[0];
}[/code]

得到byte数组后,直接写入到指定类型的文件。
[code="java"]try {
FileOutputStream fos3 = new FileOutputStream("D://tmp/mailTest/outTest.txt");
PrintWriter out3 = new PrintWriter(fos3);
out3.print(new String(bytes));
out3.flush();
out3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}[/code]

  • 写回答

1条回答 默认 最新

  • 「已注销」 2013-07-23 14:35
    关注

    你都得到bytes了,还废那么多事情用writer写干嘛。。。直接写字节就是原文件内容啊

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)