java.io.FileInputStream

by huangsb on February 26th, 2012
No notes
Syntax: Java
Show lines - Hide lines - Show in textbox - Download
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5.  
  6. public class Test {
  7.  
  8. public static void main(String[] args) {
  9. FileInputStream in = null;
  10. try {
  11. // using Constructor FileInputStream(File file)
  12. in = new FileInputStream("NewFile.txt");
  13. // using Constructor FileInputStream(String name)
  14. // File file = new File("SampleFile.txt");
  15. // in = new FileInputStream(file);
  16.  
  17. byte[] buffer1 = new byte[] {'*','*'};
  18. byte[] buffer2 = new byte[] {'*','*','*','*','*'};
  19. int count;
  20. // 顯示剩餘可讀的 Byte 總數
  21. System.out.println("in.available()=" + in.available());
  22. // int read()
  23. System.out.printf("in.read()%n=>(%s)%n", (char)in.read());
  24. // int read(byte[] b)
  25. count = in.read(buffer1);
  26. System.out.printf("count = in.read(buffer1)%n=> buffer1=(%s), count=%d%n",
  27. new String(buffer1), count);
  28. // int read(byte[] b, int off, int len)
  29. count = in.read(buffer2, 2, 2);
  30. System.out.printf("count = in.read(buffer2, 2, 2)%n=> buffer2=(%s), count=%d%n",
  31. new String(buffer2), count);
  32. // long skip(long n)
  33. count = (int)in.skip(2);
  34. // skip 通常會傳回 n, 即使超過了 EOF, 也不會有 Exception,
  35. // 但可會造成 available()傳回負數的值, 而 read method 也會傳回 -1
  36. System.out.printf("count = in.skip(2)%n=> count=%d%n", count);
  37. System.out.printf("in.read()=>(%d)%n", in.read());
  38.  
  39. System.out.println(in.getFD().valid());
  40.  
  41. System.out.println("in.available()=" + in.available());
  42.  
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. } finally {
  46. try {
  47. if (in != null)
  48. in.close();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. }
  55.  

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS