当前位置:   article > 正文

利用BufferedInputStream bufferedOutputStream读写文件_用bufferinputstream,bufferedoutputstream完成文件的读入

用bufferinputstream,bufferedoutputstream完成文件的读入
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. public class FileTools {
  9. public static byte[] readFile(String string) {
  10. FileInputStream fileInputStream=null;
  11. BufferedInputStream bufferedInputStream=null;
  12. ByteArrayOutputStream bao=new ByteArrayOutputStream();
  13. byte[] buff=new byte[1024];
  14. try {
  15. fileInputStream=new FileInputStream(string);
  16. bufferedInputStream=new BufferedInputStream(fileInputStream);
  17. int bytesRead=0;
  18. while (-1!=(bytesRead=bufferedInputStream.read(buff,0,buff.length))) {
  19. bao.write(buff,0,bytesRead);
  20. }
  21. } catch (FileNotFoundException e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. } catch (IOException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }finally{
  28. try {
  29. fileInputStream.close();
  30. bufferedInputStream.close();
  31. buff=null;
  32. } catch (IOException e) {
  33. // TODO Auto-generated catch block
  34. e.printStackTrace();
  35. }
  36. }
  37. return bao.toByteArray();
  38. }
  39. public static void writeFile(String string,byte[] bytes) {
  40. FileOutputStream fileOutputStream=null;
  41. BufferedOutputStream bufferedOutputStream=null;
  42. try{
  43. fileOutputStream=new FileOutputStream(string);
  44. bufferedOutputStream =new BufferedOutputStream(fileOutputStream);
  45. bufferedOutputStream.write(bytes);
  46. } catch (IOException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }finally{
  50. try {
  51. bufferedOutputStream.flush();
  52. fileOutputStream.close();
  53. bufferedOutputStream.close();
  54. } catch (IOException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }


原文地址

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/147131
推荐阅读
相关标签
  

闽ICP备14008679号