字节的数据是以byte类型为主实现的操作,在进行字节内容输出的时候可以使用OutputStream类完成,类的基本定义:
public abstract class OutputStream extends Object implements Closeable,Flushable
首先可以发现这个类实现了两个接口,于是基本定对应关系如下:
Closeable | Flushable |
public interface Closeable extends AutoCloseable{ public void close() throws IOException; } | public interface Flushable { public void flush throws IOException; } |
OutputStream是一个公共的输出标准,而在这个操作标准里面一共定义有三个内容输出的方法。
- public abstract void write (int b) throws IOException;输出单个字节数据
- public void write(byte[] b) throws IOException;输出一组字节数据
- public void write(byte[] b,int off,int len)throws IOException;输出部分字节数据
OutputStream类毕竟是一个抽象类,而这个抽象类如果想获得实例化对象,按照传统的认识应该通过子类实例的向上转型完成。
如果说现在要进行的是文件处理操作,则可以使用FileOutputStream子类,
【覆盖】构造方法:punlic FileOutputStream(File file) throws FileNotFoundException;
【追加】构造方法:public FileOutputStream(File file,boolean append) throws FileNotFoundException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Test000 {
public static void main(String[] args) throws Exception{
File file=new File("D:"+File.separator+"Hello"+File.separator+"mldn.txt");//1.指定文件路径
if(!file.getParentFile().exists()){//文件不存在
file.getParentFile().mkdirs();//创建父目录
}
OutputStream output=new FileOutputStream(file);//2.通过子类实例化
String str="www.mldn.cn";//要输出文件的内容
output.write(str.getBytes());//3.将字符串变为字节数组
output.close();//4。关闭资源
}
}
本程序是采用了最为标准的形式实现了输出的操作处理,并且在整体之中,只是创建了文件的父目录,但是并没有创建文件,而在执行后,文件可以自动帮助用户创建。