2)Java對數據的操作是通過流的方式。
3)Java用於操作流的對象都在IO包中。
4)流按操作數據分爲兩種:字節流和字符流。
5)流按流向分爲:輸入流和輸出流。
注意:流只能操作數據,而不能操作文件。字符流只用於處理文字數據,而字節流可以處理任何數據。
3、IO流的常用基類:
1)字節流的抽象基流:InputStream和OutputStream
2)字符流的抽象基流:Reader和Writer
注:此四個類派生出來的子類 名稱都是以父類名作爲子類名的後綴,以前綴爲其功能;如InputStream子類FileInputStream;Reader子類FileReader
c、調用flush()方法,刷新該流的緩衝,將數據刷新到目的地中。
d、調用close()方法,關閉流資源。但是關閉前會刷新一次內部的緩衝數據,並將數據刷新到目的地中。
close()和flush()區別: flush()刷新後,流可以繼續使用;而close()刷新後,將會關閉流,不可再寫入字符流。
import java.io.*;
classFileWriterDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
//創建一個FileWriter對象,該對象一被初始化,就必須要明確被操作的文件。
//而且該文件會被創建到指定目錄下。如果該目錄下如果已有同名文件,將被覆蓋。
//其實該步就是在明確數據要存放的目的地。
FileWriter fw =newFileWriter("demo.txt");
//調用write方法,將字符串寫入到流中。
fw.write("abcde");
//刷新流對象中緩衝中的數據,將數據刷新到目的地中。
fw.flush();
//關閉流資源。但是關閉前會刷新一次內部的緩衝數據,並將數據刷新到目的地中。
//close()和flush()區別:flush刷新後,流可以繼續使用;而close刷新後,將會關閉流。
fw.close();
//fw.write("gkjfkmk");
//傳遞一個true參數,代表不覆蓋已有的文件。並在已有文件的末尾處進行數據續寫。
FileWriter fw1 =newFileWriter("demo.txt",true);
//windows系統中的文件內換行用\r\n兩個轉義字符表示,在linux系統中只用\n表示換行
fw1.write("\r\nnishishui");
fw1.close();
}
}
import java.io.*;
classFileReaderDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
//創建一個文件讀取流對象,和指定名稱的文件相關聯。
//要保證該文件已經存在,若不存在,將會發生異常FileNotFoundException。
FileReader fr =newFileReader("demo.txt");
//read_1(fr);
read_2(fr);
fr.close();
}
publicstaticvoid read_1(FileReader fr)throwsIOException
{
//調用讀取流對象的read()方法。read():一次讀一個字符,且會繼續往下讀。
int ch =0;
while((ch=fr.read())!=-1)
{
System.out.println((char)ch);
}
}
publicstaticvoid read_2(FileReader fr)throwsIOException
{
//定義一個字符數組。用於存儲讀到的字符。
//該read(char[])返回的是讀到的字符個數。
char[] buf =newchar[1024];
int num =0;
while((num=fr.read(buf))!=-1)
{
System.out.println(newString(buf,0,num));
}
}
}
import java.io.*;
classFileWriterDemo1
{
publicstaticvoid main(String[] args)
{
FileWriter fw =null;
try
{
fw =newFileWriter("demo.txt");
fw.write("abcdefgh");
}
catch(IOException e)
{
System.out.println(e.toString());
}
finally
{
try
{
if(fw!=null)
fw.close();
}
catch(IOException e)
{
System.out.println(e.toString());
}
}
}
}
/*
將c盤一個文本文件複製到d盤。
複製的原理:其實就是將c盤下的文件數據存儲到d盤的一個文件中。
步驟:
1、在d盤創建一個文件。用於存儲c盤文件中的數據。
2、定義讀取流和c盤文件關聯。
3、通過不斷的讀寫完成數據存儲。
4、關閉資源。
*/
import java.io.*;
classCopyText
{
publicstaticvoid main(String[] args)
{
copy_2();
}
publicstaticvoid copy_2()
{
FileWriter fw =null;
FileReader fr =null;
try
{
fw =newFileWriter("D:\\CopyText.txt");
fr =newFileReader("C:\\CopyText.java");
char[] buf =newchar[1024];
int len =0;
while((len=fr.read(buf))!=-1)
{
fw.write(buf,0,len);
}
}
catch(IOException e)
{
thrownewRuntimeException("讀寫失敗");
}
finally
{
if(fr!=null)
try
{
fr.close();
}
catch(IOException e)
{
thrownewRuntimeException("讀關閉失敗");
}
if(fw!=null)
try
{
fw.close();
}
catch(IOException e)
{
thrownewRuntimeException("寫關閉失敗");
}
}
}
//從C盤讀一個字符,就往D盤寫一個字符。
publicstaticvoid copy_1()throwsIOException
{
//創建目的地。
FileWriter fw =newFileWriter("D:\\CopyText.txt");
//與已有文件關聯。
FileReader fr =newFileReader("C:\\CopyText.java");
int ch =0;
while((ch=fr.read())!=-1)
{
fw.write(ch);
}
fw.close();
fr.close();
}
}
如:bufw.write("adfg");
記住,只要用到緩衝區,就要記得刷新。(關閉流同樣會刷新,但爲了排除意外事故,保證數據存在,建議寫入一次就刷新一次)
如:bufw.flush();
d、其實關閉緩衝區,就是在關閉緩衝區中的流對象。
如: bufw.close();
/*
緩衝區的出現是爲了提高流的操作效率,所以在創建緩衝區之前,必須先有流對象。
該緩衝區中提供了一個跨平臺的換行符 newLine();
*/
import java.io.*;
classBufferWriterDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
//創建一個字符寫入流對象。
FileWriter fw =newFileWriter("buf.txt");
//爲了提高字符寫入流效率。加入了緩衝技術。
//只要將需要被提高效率的流對象作爲參數傳遞給緩衝區的構造函數即可。
BufferedWriter bw =newBufferedWriter(fw);
for(int x=0; x<5; x++)
{
bw.write("abcd"+x);
bw.newLine();
bw.flush();
}
//記住,只要用到緩衝區,就要記得刷新。
//其實關閉緩衝區就是在關閉緩衝區中的流對象。
bw.close();
}
}
a、創建一個讀取流對象和文件相關聯
如: FileReader fr=newFileReader("buf.txt");
b、爲了提高效率。加入緩衝技術。將字符讀取流對象作爲參數傳遞給緩衝區對象的構造函數。
如: BufferedReader bufr=new BufferedReader(fr);
如: String s=bufr.readLine();
如: bufr.close();
/*
字符流讀取緩衝區:
該緩衝區提供了一個一次讀一行的方法 readLine();方便於對文本數據的獲取。
當返回null時,表示讀到文件末尾。
注意:readLine()方法只返回回車符之前的數據內容,並不返回回車符。
*/
import java.io.*;
classBufferReaderDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
//創建一個字符讀取流對象和文件相關聯。
FileReader fr =newFileReader("buf.txt");
//爲了提高字符讀取流效率。加入了緩衝技術。
//只要將需要被提高效率的流對象作爲參數傳遞給緩衝區的構造函數即可。
BufferedReader br =newBufferedReader(fr);
String line =null;
while((line=br.readLine())!=null)
{
System.out.println(line);
}
br.close();
}
}
/*
通過緩衝區複製文件
*/
import java.io.*;
classCopyTextByBuf
{
publicstaticvoid main(String[] args)
{
BufferedWriter bw =null;
BufferedReader br =null;
try
{
bw =newBufferedWriter(newFileWriter("d:\\CopyTextByBuf.txt"));
br =newBufferedReader(newFileReader("CopyText.java"));
String line =null;
while((line=br.readLine())!=null)
{
bw.write(line);
bw.newLine();
bw.flush();
}
}
catch(IOException e)
{
thrownewRuntimeException("讀寫失敗");
}
finally
{
if(br!=null)
try
{
br.close();
}
catch(IOException e)
{
thrownewRuntimeException("讀關閉失敗");
}
if(bw!=null)
try
{
bw.close();
}
catch(IOException e)
{
thrownewRuntimeException("寫關閉失敗");
}
}
}
}
setLineNumber();//設置初始行號
getLineNumber();//獲取行號
import java.io.*;
classLineNumberReaderDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
FileReader fr =newFileReader("buf.txt");
LineNumberReader lnr =newLineNumberReader(fr);
String line =null;
lnr.setLineNumber(10);//設置初始行號
while((line=lnr.readLine())!=null)
{
System.out.println(lnr.getLineNumber()+":"+line);//獲取行號
}
lnr.close();
}
}
//模擬BufferReader
import java.io.*;
classMyBufferReaderextendsReader
{
privateReader r;
MyBufferReader(Reader r)
{
this.r = r;
}
//可以一次讀一行數據的方法。
publicString myReadLine()throwsIOException
{
//定義一個臨時容器。原BufferReader封裝的是字符數組。
//爲了演示方便。定義一個StringBuilder容器。因爲最終還是要將數據變成字符串。
StringBuilder sb =newStringBuilder();
int ch =0;
while((ch=r.read())!=-1)
{
if(ch=='\r')
continue;
if(ch=='\n')
return sb.toString();
else
sb.append((char)ch);
}
if(sb.length()!=0)
return sb.toString();
returnnull;
}
//覆蓋Reader類中的抽象方法。
publicint read(char[] cbuf,int off,int len)throwsIOException
{
return r.read(cbuf,off,len);
}
publicvoid close()throwsIOException
{
r.close();
}
publicvoid myClose()throwsIOException
{
r.close();
}
}
classMyBufferReaderDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
FileReader fr =newFileReader("buf.txt");
MyBufferReader myBuf =newMyBufferReader(fr);
String line =null;
while((line=myBuf.myReadLine())!=null)
{
System.out.println(line);
}
myBuf.myClose();
}
}
import java.io.*;
classMyLineNumberReaderextendsMyBufferReader
{
privateint lineNumber;
MyLineNumberReader(Reader r)
{
super(r);
}
publicString myReadLine()throwsIOException
{
lineNumber++;
returnsuper.myReadLine();
}
publicvoid setLineNumber(int lineNumber)
{
this.lineNumber = lineNumber;
}
publicint getLineNumber()
{
return lineNumber;
}
}
classMyLineNumberReaderDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
FileReader fr =newFileReader("buf.txt");
MyLineNumberReader lnr =newMyLineNumberReader(fr);
String line =null;
lnr.setLineNumber(10);
while((line=lnr.readLine())!=null)
{
System.out.println(lnr.getLineNumber()+":"+line);
}
lnr.MyClose();
}
}<span style="font-family: 'Microsoft YaHei'; color: rgb(190, 190, 197);"> </span>
import java.io.*;
classFileStream
{
publicstaticvoid main(String[] args)throwsIOException
{
readFile_3();
}
publicstaticvoid readFile_3()throwsIOException
{
FileInputStream fis =newFileInputStream("fos.txt");
byte[] buf =newbyte[fis.available()];//定義一個剛剛好的緩衝區,不用循環了。
//不過不建議使用,文件過大時,此數組長度所佔內存空間就會溢出。
fis.read(buf);
System.out.println(newString(buf));
fis.close();
}
publicstaticvoid readFile_2()throwsIOException
{
FileInputStream fis =newFileInputStream("fos.txt");
byte[] buf =newbyte[1024];
int len =0;
while((len=fis.read(buf))!=-1)
{
System.out.println(newString(buf,0,len));
}
fis.close();
}
publicstaticvoid readFile_1()throwsIOException
{
FileInputStream fis =newFileInputStream("fos.txt");
int ch =0;
while((ch=fis.read())!=-1)
{
System.out.println((char)ch);
}
fis.close();
}
publicstaticvoid writeFile()throwsIOException
{
FileOutputStream fos =newFileOutputStream("fos.txt");
fos.write("abcde".getBytes());
//不需要刷新操作。
fos.close();
}
}
import java.io.*;
classCopyPic
{
publicstaticvoid main(String[] args)
{
FileOutputStream fos =null;
FileInputStream fis =null;
try
{
fos =newFileOutputStream("D:\\2.JPG");
fis =newFileInputStream("D:\\1.JPG");
byte[] buf =newbyte[1024];
int len =0;
while((len=fis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
}
catch(IOException e)
{
thrownewRuntimeException("複製失敗"+ e.toString());
}
finally
{
if(fis!=null)
try
{
fis.close();
}
catch(IOException e)
{
thrownewRuntimeException("讀關閉失敗");
}
if(fos!=null)
try
{
fos.close();
}
catch(IOException e)
{
thrownewRuntimeException("寫關閉失敗");
}
}
}
}
import java.io.*;
classBufferStream
{
publicstaticvoid main(String[] args)throwsIOException
{
long start =System.currentTimeMillis();
copy_2();
long end =System.currentTimeMillis();
System.out.println((end-start)+"毫秒");
}
publicstaticvoid copy_1()throwsIOException
{
MyBufferedInputStream bis =newMyBufferedInputStream(newFileInputStream("D:\\1.JPG"));
BufferedOutputStream bos =newBufferedOutputStream(newFileOutputStream("D:\\2.JPG"));
int b =0;
while((b=bis.myRead())!=-1)
{
bos.write(b);
}
bos.close();
bis.myClose();
}
publicstaticvoid copy_2()throwsIOException
{
BufferedInputStream bis =newBufferedInputStream(newFileInputStream("D:\\1.JPG"));
BufferedOutputStream bos =newBufferedOutputStream(newFileOutputStream("D:\\2.JPG"));
int b =0;
while((b=bis.read())!=-1)
{
bos.write(b);
}
bos.close();
bis.close();
}
}
write():會將int型強轉爲byte型,即保留二進制數的最後八位。
import java.io.*;
classMyBufferedInputStream
{
privateInputStream in;
privatebyte[] buf =newbyte[1024];
privateint pos =0,count =0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
//一次讀一個字節,從緩衝區(字節數組)獲取。
publicint myRead()throwsIOException
{
//通過in對象讀取硬盤上數據,並存在buf中。
if(count==0)
{
count = in.read(buf);
if(count<0)
return-1;
pos =0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
elseif(count>0)
{
byte b = buf[pos];
count--;
pos++;
return b&0xff;
}
return-1;
}
publicvoid myClose()throwsIOException
{
in.close();
}
}
import java.io.*;
classTransStreamDemo
{
publicstaticvoid main(String[] args)throwsIOException
{
transStream();
}
/*
讀取鍵盤錄入
System.out:對應的標準輸出設備:控制檯
System.in:對應的標準輸入設備:鍵盤
需求:
通過鍵盤錄入數據
當錄入一行數據後,就將該行數據進行打印。
如果錄入的數據是over,那麼停止錄入。
*/
publicstaticvoid readIn()throwsIOException
{
InputStream in =System.in;
StringBuilder sb =newStringBuilder();
while(true)
{
int ch = in.read();
if(ch=='\r')
continue;
if(ch=='\n')
{
String s = sb.toString();
if("over".equals(s))
break;
System.out.println(s.toUpperCase());
sb.delete(0,sb.length());
}
else
sb.append((char)ch);
}
}
/*
通過剛纔的鍵盤錄入一行數據並打印其大寫,發現其實就是讀一行數據的原理。
也就是readLine方法。
能不能直接使用readLine方法來完成鍵盤錄入的一行數據的讀取呢?
readLine方法是字符流BufferedReader類中方法。
而鍵盤錄入的read方法是字節流InputStream的方法。
那麼能不能將字節流轉成字符流再使用字符流緩衝區的readLine方法呢?
*/
publicstaticvoid transStream()throwsIOException
{
/*//獲取鍵盤錄入對象。
InputStream in = System.in;
//將字節流對象轉成字符流對象,使用轉換流。InputStreamReader
InputStreamReader isr = new InputStreamReader(in);
//爲了提高效率,將字符串進行緩衝區技術高效操作。使用BufferedReader
BufferedReader br = new BufferedReader(isr);
*/
//鍵盤的最常見寫法
BufferedReader br =newBufferedReader(newInputStreamReader(System.in));
/*
OutputStream out = System.out;
OutputStreamWriter osw = new OutputStreamWriter(out);
BufferedWriter bw = new BufferedWriter(osw);
*/
BufferedWriter bw =newBufferedWriter(newOutputStreamWriter(System.out););
String line =null;
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
//System.out.println(line.toUpperCase());
bw.write(line.toUpperCase());
bw.newLine();
bw.flush();
}
br.close();
}
}
源:輸入流。InputStream Reader
目的:輸出流。OutputStream Writer
b 操作的數據是否是純文本。
是:字符流
否:字節流
c 當體系明確後,再明確要使用哪個具體的對象。通過設備來進行區分:
源設備:內存,硬盤,鍵盤
目的設備:內存,硬盤,控制檯
/*
需求:將鍵盤錄入的數據按照指定編碼表UTF-8保存到一個文件中。
1)源:InputStream和Reader
是不是純文本?是,Reader
設備:鍵盤。對應的對象是System.in。
既然明確了Reader,那麼就將System.in轉換成Reader。用Reader體系中轉換流,InputStreamReader
InputStreamReaderisr = new InputStreamReader(System.in);
需要提高效率嗎?需要,BufferedReader
BufferedReader br = new BufferedReader(isr);
2)目的:OutputStream Writer
是否是存文本?是!Writer。
設備:硬盤。一個文件。使用 FileWriter。但是FileWriter是使用的默認編碼表:GBK。
而存儲時,需要加入指定編碼表utf-8。而指定的編碼表只有轉換流可以指定。所以要使用的對象是OutputStreamWriter。
OutputStreamWriter要接收一個字節輸出流,而且還可以操作的文件的字節輸出流:FileOutputStream
OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("d.txt"),"UTF-8");
需要提高效率嗎?需要。
BufferedWriter bufw = new BufferedWriter(osw);
*/
import java.io.*;
class UTF
{
publicstaticvoid main(String[] args)throwsIOException
{
//鍵盤錄入
BufferedReader br =newBufferedReader(newInputStreamReader(System.in));
//按照指定編碼表UTF-8存入文件中
BufferedWriter bw =newBufferedWriter(newOutputStreamWriter(newFileOutputStream("utf.txt"),"UTF-8"));
String line =null;
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
//System.out.println(line.toUpperCase());
bw.write(line.toUpperCase());
bw.newLine();
bw.flush();
}
br.close();
}
}
import java.io.*;
import java.util.*;
import java.text.*;
classExceptionInfo
{
publicstaticvoid main(String[] args)throwsIOException
{
try
{
int[] arr =newint[2];
System.out.println(arr[3]);
}
catch(Exception e)
{
Date d =newDate();
SimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = sdf.format(d);
PrintStream ps =newPrintStream("exception.log");
ps.println(s);
System.setOut(ps);
e.printStackTrace(System.out);
}
}
}
import java.io.*;
import java.util.*;
classSystemInfo
{
publicstaticvoid main(String[] args)throwsIOException
{
Properties prop =System.getProperties();
//Systen.out.println(prop);
prop.list(newPrintStream("systeminfo.txt"));
}
}