Java基础之IO流

Java IO流简介

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

OutputStream:

public abstract class OutputStream
extends Object
implements Closeable, Flushable
All Implemented Interfaces:
CloseableFlushableAutoCloseable
Direct Known Subclasses:
ByteArrayOutputStreamFileOutputStreamFilterOutputStreamObjectOutputStreamOutputStreamPipedOutputStream
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 Type Method and Description
voidclose()
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 InputStream
extends Object
implements 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 Type Method and Description
intavailable()
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 Writer
extends Object
implements 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.
  • Field Summary

    Modifier and Type Field and Description
    protected Objectlock
    The object used to synchronize operations on this stream.
  • Constructor Summary

    Modifier Constructor and Description
    protectedWriter()
    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 Type Method and Description
    Writerappend(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 Reader
extends Object
implements 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 Type Field and Description
    protected Objectlock
    The object used to synchronize operations on this stream.
  • Constructor Summary

    Modifier Constructor and Description
    protectedReader()
    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 Type Method and Description
    abstract 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();
   }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值