其他分享
首页 > 其他分享> > 字节流

字节流

作者:互联网

1  字节流抽象基类

       InputStream  字节输入流所有类的超类

       OutputStream 字节输出流所有类的超类

 2  FileOutputStream(String name)  创建文件输出流以指定的名称写入文件

     void close()  关闭此文件输出流并释放与此流相关联的任何系统资源

public class demo1 {
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("fos.txt");
fos.write(97);
fos.close();
}

3  字节流写数据的三种方式

   void write(int b) 将指定的字节写入此文件输出流,一次写一个字节数据

   void write(byte[] b) 将b.length字节从指定的字节数组写入此文件输出流,一次写一个字节数组数据

public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("fos.txt");
byte[] bys= {97,98,99,100};          //另一种创建字节数组的方法 byte[] getBytes()  返回字符串对应的字节数组
fos.write(bys);                              //byte[] bys="abcd".getBytes();

fos.close();                                  
}

   void write(byte[] b,int off,int len)将len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流

                                                     一次写一个字节数组的部分数据

byte[] bys="abcd".getBytes();

fos.write(bys,0,bys.length);

fos.close();

4  字节流写数据如何换行

     字节流写数据如何追加

public FileOutputStream(String name,boolean append)

             创建文件输出流以指定的名称写入文件,

             如果第二个参数是true,字节将写入文件的末尾,而不是开头

public class demo1 {
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("fox.txt",true);
byte[] bys="hello".getBytes();
for(int i=0;i<10;i++)
{
fos.write(bys);
fos.write("\n".getBytes());


}
fos.close();
}

 5  字节流写数据加异常处理

package com;
import java.io.FileOutputStream;
import java.io.IOException;
public class demo {
   public static void main(String[] args)
   {
        FileOutputStream fos=null;//fos如果在下面的try里定义,finally里没法用
        try {
              fos=new FileOutputStream("fos.txt");
              fos.write("hello".getBytes());
            }catch(IOException e)
         {
             e.printStackTrace();
          }finally {
              if(fos!=null)//防止空指针异常
               {
               try {
                     fos.close();
               }catch(IOException e)
               {
                    e.printStackTrace();
                }
                }
           }
      }

}

标签:字节,fos,void,bys,write,FileOutputStream
来源: https://www.cnblogs.com/zlyyds/p/15240272.html