问题描述
问题:如题!!!!!我现在是用java读取了txt、word、execl三种类型的文件。并且得到他们的二进制流(也就是byte数组)。我要怎么通过这个byte数组写入到这些类型的文件中(注:内容不变、文件类型不变、总之所有的东西都不变,还是原来一模一样的东西)。请问我应该怎么实现呢?读取文件代码,并且得到byte[].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]; }得到byte数组后,直接写入到指定类型的文件。try {FileOutputStream fos3 = new FileOutputStream("D://tmp/mailTest/outTest.txt");PrintWriterout3 = new PrintWriter(fos3);out3.print(new String(bytes));out3.flush();out3.close();} catch (FileNotFoundException e) {e.printStackTrace();}
解决方案
你都得到bytes了,还废那么多事情用writer写干嘛。。。直接写字节就是原文件内容啊