java BIO 读取文件和写出到文件

Bertha 。 2022-03-09 04:40 224阅读 0赞
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. public class BIOTest {
  8. // public static void main(String[] args) {
  9. // try {
  10. // //BIO方式读取文件
  11. // String pathname = "D:\\add.txt";
  12. // File file = new File(pathname);
  13. // FileInputStream fileInputStream = new FileInputStream(file);
  14. // BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
  15. // //相对当前位置的偏移量
  16. // int off = 0;
  17. // //读取的长度,单位为字节
  18. // int len = 1024;
  19. // //读取的数据存储到该字节数组
  20. // //数组初始化之后,会有1024个字节,默认值为0。所以下面读取数据到b字节数组的时候,假如读取的长度不够,会有0填充的问题。
  21. // //所以具体要从b中读取多少个数据,要看len= bufferedInputStream.read(b, off, len)中,b到底从输入流中读取到了多少字节,也就是Len的值为多少
  22. // //以下的写法就是正常的,不会出现message中有乱码或者0填充的情况。
  23. // byte[] b = new byte[1024];
  24. // String message = "";
  25. // while ((len= bufferedInputStream.read(b, off, len)) != -1) {
  26. // message = message + new String(b, 0, len);
  27. // //这种写法就是错误的,会出现0填充的情况
  28. // //message = message + new String(b);
  29. // }
  30. // System.out.println(message);
  31. // bufferedInputStream.close();
  32. // fileInputStream.close();
  33. // } catch (Exception e) {
  34. // e.printStackTrace();
  35. // }
  36. // }
  37. public static void main(String[] args) {
  38. try {
  39. //BIO方式读取文件,写出文件
  40. String pathname = "D:\\add.txt";
  41. File file = new File(pathname);
  42. FileInputStream fileInputStream = new FileInputStream(file);
  43. BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
  44. FileOutputStream fileOutputStream = new FileOutputStream("D:\\add222.txt");
  45. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
  46. //相对当前位置的偏移量
  47. int off = 0;
  48. //读取的长度,单位为字节
  49. int len = 1024;
  50. //读取的数据存储到该字节数组
  51. //数组初始化之后,会有1024个字节,默认值为0。所以下面读取数据到b字节数组的时候,假如读取的长度不够,会有0填充的问题。
  52. //所以具体要从b中读取多少个数据,要看len= bufferedInputStream.read(b, off, len)中,b到底从输入流中读取到了多少字节,也就是Len的值为多少
  53. //以下的写法就是正常的,不会出现message中有乱码或者0填充的情况。
  54. byte[] b = new byte[1024];
  55. while ((len= bufferedInputStream.read(b, off, len)) != -1) {
  56. bufferedOutputStream.write(b, 0, len);
  57. }
  58. bufferedInputStream.close();
  59. fileInputStream.close();
  60. bufferedOutputStream.close();
  61. fileOutputStream.close();
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. }

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读