java.io.FileInputStream

by huangsb on February 26th, 2012
No notes
Syntax: Java
Show lines - Hide lines - Show in textbox - Download
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class Test {
 
    public static void main(String[] args) {
        FileInputStream in = null;
        try {
            // using Constructor FileInputStream(File file)
            in = new FileInputStream("NewFile.txt");
            // using Constructor FileInputStream(String name) 
            // File file = new File("SampleFile.txt");
            // in = new FileInputStream(file);
 
            byte[] buffer1 = new byte[] {'*','*'};
            byte[] buffer2 = new byte[] {'*','*','*','*','*'};
            int count;
            // 顯示剩餘可讀的 Byte 總數
            System.out.println("in.available()=" + in.available());
            // int read()
            System.out.printf("in.read()%n=>(%s)%n", (char)in.read());
            // int read(byte[] b)
            count = in.read(buffer1);
            System.out.printf("count = in.read(buffer1)%n=> buffer1=(%s), count=%d%n",
                    new String(buffer1), count);
            // int read(byte[] b, int off, int len)
            count = in.read(buffer2, 2, 2);
            System.out.printf("count = in.read(buffer2, 2, 2)%n=> buffer2=(%s), count=%d%n",
                    new String(buffer2), count);
            // long skip(long n)
            count = (int)in.skip(2);
            // skip 通常會傳回 n, 即使超過了 EOF, 也不會有 Exception, 
            // 但可會造成 available()傳回負數的值, 而 read method 也會傳回 -1
            System.out.printf("count = in.skip(2)%n=> count=%d%n", count);
            System.out.printf("in.read()=>(%d)%n", in.read());
 
            System.out.println(in.getFD().valid());
 
            System.out.println("in.available()=" + in.available());
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 

Leave a Reply

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

Subscribe to this comment feed via RSS