java _io_文件输出

1、创建源
2、选择流
3、操作(写出)
4、刷新缓存,避免数据驻留内存
5、释放资源

File f =new File("D:/d/t.txt"); //文件不存在stream流会自动创建
OutputStream os=new FileOutputStream(f,true) //添加布尔类型true,会开启追加模式,
默认为false。
byte[] data =s.getBytes() //编码
os.write(byte[] data) //写出字节数组的内容
os.write(byte[] data,0,length) //写出从索引位置0处偏移length长度的内容

public class test{

public static void main(String[]args) 
{
    //创建源
    File f =new File("D:/d/t.txt");  //文件不存在stream流会自动创建
    //选择流
    OutputStream os =null;
    try {
        os =new FileOutputStream(f,true);
        //os =new FileOutputStream(f,true);  //添加布尔类型true ,将会开启追加模式
        //操作(写出),通过字节数组写出
        String s="hello world";

        byte[] data=s.getBytes();
        try {
            //os.write(data);
            os.write(data,0,data.length);
            //刷新数据,避免数据驻留在内存中
            os.flush();
        } catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }
    finally {
        //释放资源
        try {
            if(null!=os)
            {
                os.close();
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }

    }

} 

}

猜你喜欢

转载自blog.51cto.com/14437184/2423123