outputstream是java中的字节输出流,它能用来将文件或者字符串输出到新的文件中,其使用方法是:首先使用file类打开一个文件;然后通过流的子类来指定位置;接着进行输入或输出操作;最后关闭“输入/输出”即可。
流是用来读写传输数据的,输入和输出是对程序本身而言的,但程序需要读入数据用读入流,程序需要将数据输出保存起来用输出流。
流相当于各种不同的管道来传输数据。按读入和输出分为输入流和输出流。按传输的类型分为字节流和字符流。按管道与管道的关系又可分为节点流与处理流。
outputstream是java中的字节输出流,它能用来将文件或者字符串输出到新的文件中。具体操作查看原文,附代码解释。
字节流中输出使用outputstream类输入使用inputstream类。
在java中流的操作分为下面4个步骤:
使用file类打开一个文件通过流的子类来指定位置进行输入或输出操作关闭输入/输出
字节输出流:outputstream
outputstream类是抽象类,其子类fileoutputstream
import java.io.file;import java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import java.io.outputstream;public class testoutputstream {private static inputstream in;private static outputstream out;public static void main(string[] args) {try {in = new fileinputstream("d:/test/testio.java");if(in == null){//原文件不存在system.out.println("原文件不存在");}else{//原文件存在,判断目标文件是否存在file file = new file("d:/test/testioo.txt");if(!file.exists()){//目标文件不存在,创建目标文件file.getparentfile().mkdirs();file.createnewfile();}//将原文件内容读取到目标文件out = new fileoutputstream(file);int a = 0;while((a = in.read()) != -1){out.write(a);}}} catch (filenotfoundexception e) {// todo auto-generated catch blocke.printstacktrace();} catch (ioexception e) {// todo auto-generated catch blocke.printstacktrace();}finally{//流关闭try {if(in != null){in.close();}if(out != null){out.close();}} catch (ioexception e) {// todo auto-generated catch blocke.printstacktrace();}}}}
通过实践,发现原先d盘中有文件,通过outputstream生成了新的文件。
以上就是java中outputstream文件输出流的用法的详细内容。
