关于文件输入流

image.png

构造方法摘要

image.png

方法摘要

image.png

示例代码

1、读取文件内容

  1. import java.io.FileInputStream;
  2. import java.io.IOException;
  3. public class Main {
  4. public static void main(String[] args) {
  5. // readFile01();
  6. readFile02();
  7. }
  8. /**
  9. * 一次读取一个字节,效率比较低
  10. */
  11. public static void readFile01() {
  12. String filePath = "./hello.txt";
  13. int data = 0;
  14. FileInputStream fileInputStream = null;
  15. try {
  16. fileInputStream = new FileInputStream(filePath);
  17. while ((data = fileInputStream.read()) != -1) {
  18. System.out.print((char) data);
  19. }
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. } finally {
  23. // 关闭文件流,释放资源。。,。,。.
  24. try {
  25. fileInputStream.close();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. /**
  32. * 一次读取 8 个字节
  33. */
  34. public static void readFile02() {
  35. String filePath = "./hello.txt";
  36. int readLen = 0;
  37. byte[] buf = new byte[8];
  38. FileInputStream fileInputStream = null;
  39. try {
  40. fileInputStream = new FileInputStream(filePath);
  41. while ((readLen = fileInputStream.read(buf)) != -1) {
  42. System.out.print(new String(buf, 0, readLen));
  43. }
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. } finally {
  47. // 关闭文件流,释放资源。。,。,。.
  48. try {
  49. fileInputStream.close();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. }