Java文件流

文件输入流类:

这是所有InputStream类的具体子类。
此类始终用于在读取模式下打开文件。
在读取模式下打开文件才能创建FileInputStream类的对象。

构造函数:

1.	FileOutputStream (String fname);
2.	FileOutputStream (String fname, boolean flag);

如果标志为真,则数据将添加到现有文件中,如果标志为false,则数据将与现有文件数据重叠。

如果文件在写入模式下打开,则FileOutputStream的对象将指向在写入模式下打开的该文件。
如果文件无法在Write模式下打开FileOutputStream的对象包含NULL。

Java文件流示例

创建一个包含1到10个数字的文件。

import java.io.*; 
class Fos
{
    public static void main (String [] args)
    {
        try
        {
            String fname=args [0];
            FileOutputStream fos=new FileOutputStream (fname, true);//mean append mode
            for (int i=1; i<=10; i++)
            {
                fos.write (i);
            }
            fos.close ();
        }
        catch (IOException ioe)
        {
            System.out.println (ioe);
        }
        catch (ArrayIndexOutOfBoundsException aiobe)
        {
            System.out.println ("PLEASE PASS THE FILE NAME..!");
        }
        System.out.println ("DATA WRITTEN..!");
    }
};

Java从文件中读取数据

import java.io.*; 
class	Fis
{
    public static void main(String[] args)
    {
        try
        {
            String fname=args [0];
            FileInputStream fis=new FileInputStream (fname);
            int i;
            while ((i=fis.read ())!=-1)
            {
                System.out.println (i);
            }
            fis.close ();
        }
        catch (FileNotFoundException fnfe)
        {
            System.out.println ("FILE DOES NOT EXIST..!");
        }
        catch (IOException ioe)
        {
            System.out.println (ioe);
        }
        catch (ArrayIndexOutOfBoundsException aiobe)
        {
            System.out.println ("PLEASE PASS THE FILE NAME..!");
        }
    }
};

构造函数:

FileInputStream (String fname) throws FileNotFoundException

例如:

FileInputStream fis=new FileInputStream ("abc.txt");

如果文件名abc.txt不存在,那么fileInputStream FIS的对象是NULL,因此我们获取FileNotFoundException。
如果文件名abc.txt存在于读取模式下将在读取模式下成功打开文件ABC.txt,并且对象FIS将指向文件的开头。

文件输出流类:

这是所有OutputStream类的具体子类。
此类始终用于在写入模式下打开文件,但仅创建FileOutputStream类的对象。

日期:2020-04-11 23:04:27 来源:oir作者:oir