Java基础之IO流

来源:互联网 发布:室内设计户型优化思路 编辑:程序博客网 时间:2024/04/30 23:11

Java IO流简介

Java的IO操作一般会涉及OutputStream 、 InputStream 、 Write  、 Read 四个操作;

OutputStream:

public abstract class OutputStreamextends Objectimplements Closeable, Flushable
All Implemented Interfaces:
Closeable, Flushable, AutoCloseable
Direct Known Subclasses:
ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream
This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

这是一个抽象类,要应用他的子类进行操作;

Method Summary

Modifier and TypeMethod and Descriptionvoidclose()
Closes this output stream and releases any system resources associated with this stream.
voidflush()
Flushes this output stream and forces any buffered output bytes to be written out.
voidwrite(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
voidwrite(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract voidwrite(int b)
Writes the specified byte to this output stream.
/*================================================= * 字节流与字符流 * IO流的JAVA操作 * OutputStream  InputStream 字节流 * Write  Reader  字符流 * 4个操作类都是抽象类 IO用完必须关闭; *===============================================*/import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;public class Demo006 {   public static void main(String args[]) throws Exception{   File file=new File("E:"+File.separator+"test.txt");   OutputStream out=null;//输出字节流   //把文件放到流中,没有会自动创建新文件   out=new FileOutputStream(file,true);//向上转型为OutputStream   //   String str="\r\n张";//换行   byte b[]=str.getBytes();   out.write(b);//写入操作   out.close();//关闭流操作;       }}

InputStream:

public abstract class InputStreamextends Objectimplements Closeable
This abstract class is the superclass of all classes representing an input stream of bytes.

Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.

跟上面的差不多,大同小异;

Method Summary

Modifier and TypeMethod and Descriptionintavailable()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
voidclose()
Closes this input stream and releases any system resources associated with the stream.
voidmark(int readlimit)
Marks the current position in this input stream.
booleanmarkSupported()
Tests if this input stream supports the mark and reset methods.
abstract intread()
Reads the next byte of data from the input stream.
intread(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.
intread(byte[] b, int off, int len)
Reads up to len bytes of data from the input stream into an array of bytes.
voidreset()
Repositions this stream to the position at the time the mark method was last called on this input stream.
longskip(long n)
Skips over and discards n bytes of data from this input stream.
import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;public class Demo007 {    public static void main(String[] args) throws IOException{    //(1)    File file =new File("E:"+File.separator+"test.txt");    //    InputStream input=null;    input=new FileInputStream(file);    // <span style="font-family: Arial, Helvetica, sans-serif;">byte b[] = new byte[(int)file.lenfth()]; //别浪费空间</span>    byte b[] = new byte[1024];    int len=input.read(b);//把文件内容读到byte[1024]中 返回读取的长度    input.close();    System.out.println("读取的长度为:"+len);    System.out.println("输出内容:"+new String(b,0,b.length));    }}
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array argument.
我们在不知到文件大小时,更多的是使用下面的范例:
import java.io.File ;import java.io.InputStream ;import java.io.FileInputStream ;public class InputStreamDemo05{public static void main(String args[]) throws Exception{// 异常抛出,不处理// 第1步、使用File类找到一个文件File f= new File("d:" + File.separator + "test.txt") ;// 声明File对象// 第2步、通过子类实例化父类对象InputStream input = null ;// 准备好一个输入的对象input = new FileInputStream(f)  ;// 通过对象多态性,进行实例化// 第3步、进行读操作byte b[] = new byte[1024] ;// 数组大小由文件决定int len = 0 ; int temp = 0 ;// 接收每一个读取进来的数据while((temp=input.read())!=-1){// 表示还有内容,文件没有读完b[len] = (byte)temp ;len++ ;}// 第4步、关闭输出流input.close() ;// 关闭输出流\System.out.println("内容为:" + new String(b,0,len)) ;// 把byte数组变为字符串输出}};

Writer:

字符输入流:字符流是一个字符串输出,不再拘泥与byte;
Demo:
import java.io.*;public class Demo010 {public static void main(String args[]) throws Exception{// 异常抛出,不处理// 第1步、使用File类找到一个文件File f= new File("E:" + File.separator + "test.txt") ;// 声明File对象// 第2步、通过子类实例化父类对象Writer out = null ;// 准备好一个输出的对象out = new FileWriter(f,true)  ;// 通过对象多态性,进行实例化// 第3步、进行写操作String str = "Hello World!!!" ;// 准备一个字符串out.write(str) ;// 将内容输出,保存文件// 第4步、关闭输出流out.close() ;// 关闭输出流}}

public abstract class Writerextends Objectimplements Appendable, Closeable, Flushable
Abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
Since:
JDK1.1
See Also:
WriterBufferedWriterCharArrayWriterFilterWriterOutputStreamWriterFileWriterPipedWriterPrintWriterStringWriterReader
  • Field Summary

    Modifier and TypeField and Descriptionprotected Objectlock
    The object used to synchronize operations on this stream.
  • Constructor Summary

    ModifierConstructor and DescriptionprotectedWriter()
    Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
    protectedWriter(Object lock)
    Creates a new character-stream writer whose critical sections will synchronize on the given object.
  • Method Summary

    Modifier and TypeMethod and DescriptionWriterappend(char c)
    Appends the specified character to this writer.
    Writerappend(CharSequence csq)
    Appends the specified character sequence to this writer.
    Writerappend(CharSequence csq, int start, int end)
    Appends a subsequence of the specified character sequence to this writer.
    abstract voidclose()
    Closes the stream, flushing it first.
    abstract voidflush()
    Flushes the stream.
    voidwrite(char[] cbuf)
    Writes an array of characters.
    abstract voidwrite(char[] cbuf, int off, int len)
    Writes a portion of an array of characters.
    voidwrite(int c)
    Writes a single character.
    voidwrite(String str)
    Writes a string.
    voidwrite(String str, int off, int len)
    Writes a portion of a string.

Reader


Demo:
import java.io.*;public class Demo011 {public static void main(String args[]) throws Exception{// 异常抛出,不处理// 第1步、使用File类找到一个文件File f= new File("E:" + File.separator + "test.txt") ;// 声明File对象// 第2步、通过子类实例化父类对象Reader input = null ;// 准备好一个输入的对象input = new FileReader(f)  ;// 通过对象多态性,进行实例化// 第3步、进行读操作char c[] = new char[1024] ;// 所有的内容都读到此数组之中int len = input.read(c) ;// 读取内容// 第4步、关闭输出流input.close() ;// 关闭输出流System.out.println("内容为:" + new String(c,0,len)) ;// 把字符数组变为字符串输出}}


public abstract class Readerextends Objectimplements Readable, Closeable
Abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
Since:
JDK1.1
See Also:
BufferedReaderLineNumberReaderCharArrayReaderInputStreamReaderFileReaderFilterReaderPushbackReaderPipedReaderStringReaderWriter
  • Field Summary

    Modifier and TypeField and Descriptionprotected Objectlock
    The object used to synchronize operations on this stream.
  • Constructor Summary

    ModifierConstructor and DescriptionprotectedReader()
    Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
    protectedReader(Object lock)
    Creates a new character-stream reader whose critical sections will synchronize on the given object.
  • Method Summary

    Modifier and TypeMethod and Descriptionabstract voidclose()
    Closes the stream and releases any system resources associated with it.
    voidmark(int readAheadLimit)
    Marks the present position in the stream.
    booleanmarkSupported()
    Tells whether this stream supports the mark() operation.
    intread()
    Reads a single character.
    intread(char[] cbuf)
    Reads characters into an array.
    abstract intread(char[] cbuf, int off, int len)
    Reads characters into a portion of an array.
    intread(CharBuffer target)
    Attempts to read characters into the specified character buffer.
    booleanready()
    Tells whether this stream is ready to be read.
    voidreset()
    Resets the stream.
    longskip(long n)
    Skips characters.
简单拷贝程序
/*================================== * 编写一个拷贝程序: * 实现方式一般我们回想到2中方式: * 1 读完再写 * 2 边读边写 * 很明显,考虑文件的大小不知,最后用2方式 *=================================*/package demoIO010;import java.io.*;import java.util.Scanner;public class Demo012 {   public static void main(String args[]) throws IOException{           File f1=new File("E:"+File.separator+"test2.txt");        File f2=new File("E:"+File.separator+"test1.txt");        if(!f1.exists()){        System.out.println("输入源文件不存在 :");            System.exit(1);        }        InputStream input=null;        OutputStream output=null;                input = new FileInputStream(f1);        output = new FileOutputStream(f2);                if(input!=null&&output!=null){        int temp=0;        while((temp=input.read())!=-1){//读字符流        output.write(temp);        }        }                input.close();        output.close();   }}






0 0
原创粉丝点击