一:输入和输出概念
输入流(inputstream):对于java程序来说,从程序写入文件叫做输出。
输出流(outputstream):对于java程序来说,从文件读取数据,到java程序叫做输入。
二:字节流输出(outputstream)
该类是抽象类,public abstract class OutputStream extends Object implements Closeable, Flushable
所以如果想调用他的方法,需要通过子类来进行调用,该类的操作是字节,所以叫做字节输出流
操作文件可以是任意文件。
1:方法:
1: close()关闭字节输出流,释放资源,类似python中操作文件,最后需要close一样。
2:write()该方法为重载方法,将相应的内容写入文件中。
3:flush()是将缓存的数据刷入永久存储(文件)中。
:2:查看其实现类:
实现类有如下:
我先来使用:FileOutoutStream类。
public class FileOutputStream
extends OutputStream
构造器:
如上构造器,通过绑定文件句柄。来实现文件操作。
1 package test14;2
3 import java.io.File;4 import java.io.FileNotFoundException;5 import java.io.FileOutputStream;6 import java.io.OutputStream;7
8 public classOutputStreamDemon {9 public static voidmain(String...args){10
11 }12 public static voidoutputStrem(File file) throws FileNotFoundException{13 FileOutputStream fps=newFileOutputStream(file);14 FileOutputStream fps1=new FileOutputStream("c:\\new");15
16 }17 }
其中append参数的含义:
如果写true表示在文本的最后追加写入。不是覆盖写入!
1 FileOutputStream fps1=new FileOutputStream("c:\\new",true);
1 package test14;2
3 import java.io.*;4
5 public classOutputStreamDemon {6 public static voidmain(String...args){7 File file=new File("c:\\new");8 try{9 outputStrem(file);10 }catch(IOException ex){11 System.out.print(ex);12 }13
14
15 }16 public static voidoutputStrem(File file) throws FileNotFoundException,IOException{17 OutputStream fps=newFileOutputStream(file);18 OutputStream fps1=new FileOutputStream("c:\\new",true);//append 默认写true 表示写入内容追加到文件末尾。
19 byte[] w_con=new byte[]{'o','k'};//写入文件内容需要字节数组。
20 fps1.write(w_con);21 fps1.write(65);//写的数字转换成字母。
22 fps1.close();//关闭文件句柄 释放资源.
23
24 }25 }
输出结果:
换行:
1 byte[] w_con=new byte[]{'o','\n','k'};//写入文件内容需要字节数组。
在写入字节的时候,写入的内容会对比ASCII表,转换成对应的值写入文件。
1 package Fileout_Demo;2
3 import java.io.File;4 import java.io.FileOutputStream;5 import java.io.IOException;6
7 public classFieloutstream_Demo {8 public static voidmain (String...args){9 try{10 write_Test();11 }catch(IOException e){12 System.out.print(e);13 }14
15 }16
17 public static voidwrite_Test() throws IOException{18 File f=new File("c:/tmp.txt");19 FileOutputStream fs=newFileOutputStream(f);20 fs.write("ok".getBytes());//将字符串转换成对应的字节数组。如果是数字的话会按照assic表来写入对应的值。
21 fs.close();22 }23
24 }