Java IO流简介
Java的IO操作一般会涉及OutputStream 、 InputStream 、 Write 、 Read 四个操作;
OutputStream:
public abstract class OutputStream extends Object implements Closeable, Flushable
-
All Implemented Interfaces:
- Closeable, Flushable, AutoCloseable
-
Direct Known Subclasses:
- ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream
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 |
---|---|
void | close()
Closes this output stream and releases any system resources associated with this stream.
|
void | flush()
Flushes this output stream and forces any buffered output bytes to be written out.
|
void | write(byte[] b)
Writes
b.length bytes from the specified byte array to this output stream.
|
void | write(byte[] b, int off, int len)
Writes
len bytes from the specified byte array starting at offset
off to this output stream.
|
abstract void | write(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 |
---|---|
int | available()
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.
|
void | close()
Closes this input stream and releases any system resources associated with the stream.
|
void | mark(int readlimit)
Marks the current position in this input stream.
|
boolean | markSupported()
Tests if this input stream supports the
mark and
reset methods.
|
abstract int | read()
Reads the next byte of data from the input stream.
|
int | read(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array
b .
|
int | read(byte[] b, int off, int len)
Reads up to
len bytes of data from the input stream into an array of bytes.
|
void | reset()
Repositions this stream to the position at the time the
mark method was last called on this input stream.
|
long | skip(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.
Since:
JDK1.1
See Also:
Writer
,
BufferedWriter
,
CharArrayWriter
,
FilterWriter
,
OutputStreamWriter
,
FileWriter
,
PipedWriter
,
PrintWriter
,
StringWriter
,
Reader
-
Field Summary
Modifier and Type Field and Description protected Object
lock
The object used to synchronize operations on this stream.
-
Constructor Summary
Modifier Constructor and Description protected
Writer()
Creates a new character-stream writer whose critical sections will synchronize on the writer itself.protected
Writer(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 Writer
append(char c)
Appends the specified character to this writer.Writer
append(CharSequence csq)
Appends the specified character sequence to this writer.Writer
append(CharSequence csq, int start, int end)
Appends a subsequence of the specified character sequence to this writer.abstract void
close()
Closes the stream, flushing it first.abstract void
flush()
Flushes the stream.void
write(char[] cbuf)
Writes an array of characters.abstract void
write(char[] cbuf, int off, int len)
Writes a portion of an array of characters.void
write(int c)
Writes a single character.void
write(String str)
Writes a string.void
write(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:
-
BufferedReader
,LineNumberReader
,CharArrayReader
,InputStreamReader
,FileReader
,FilterReader
,PushbackReader
,PipedReader
,StringReader
,Writer
-
Field Summary
Modifier and Type Field and Description protected Object
lock
The object used to synchronize operations on this stream.
-
Constructor Summary
Modifier Constructor and Description protected
Reader()
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.protected
Reader(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 void
close()
Closes the stream and releases any system resources associated with it.void
mark(int readAheadLimit)
Marks the present position in the stream.boolean
markSupported()
Tells whether this stream supports the mark() operation.int
read()
Reads a single character.int
read(char[] cbuf)
Reads characters into an array.abstract int
read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.int
read(CharBuffer target)
Attempts to read characters into the specified character buffer.boolean
ready()
Tells whether this stream is ready to be read.void
reset()
Resets the stream.long
skip(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();
}
}