java中讲讲FileInputStream的用法

FileInputStream的用法
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
FileInputStream是InputStream的继承类,从字面上就可看出,它的主要功能就是能从磁盘上读入文件。read方法会一个一个字节的从磁盘往回读数据。



例:2.2.1

import java.io.*;
public class TestMark_to_win {
    public static void main(String args[]) throws Exception {
        int size;
        FileInputStream f1 = new FileInputStream("c:/1.txt");
        /*Returns the number of bytes that can be read from this file input
stream without blocking.*/
        size = f1.available();
        for (int i = 0; i < size; i++) {
            /*Reads a byte of data from this input stream. This method blocks
if no input is yet available. Returns: the next byte of data, or
-1 if the end of the file is reached.*/
            System.out.println((char) f1.read());

        }

        int size2;
        FileInputStream f2 = new FileInputStream("c:/1.txt");
        size2 = f2.available();
        for (int i = 0; i < size2; i++) {
            /* you use the next statement, only int value can be printed out. */
            System.out.println(f2.read());

        }

    }
}

我的c盘下的1.txt文本是:

ab我们ab


程序运行结果是:

a
b
?
?
?
?
a
b
97
98
206
210
195
199
97
98




例:2.2.2(下面是一个较笨的拷贝程序,初学者好理解)
import java.io.*;
public class TestMark_to_win {
    public static void main(String[] args) throws IOException {
        File inputFile = new File("i:/1.txt");
        File outputFile = new File("i:/1_c.txt");
        FileInputStream in = new FileInputStream(inputFile);
        FileOutputStream out = new FileOutputStream(outputFile);
        int c;
        while ((c = in.read()) != -1)
            out.write(c);
        in.close();
        out.close();
    }
}