Java語(yǔ)言的打開(kāi)文件和寫(xiě)入文件
1、Java語(yǔ)言打開(kāi)文件
本例以FileInputStream的read(buffer)方法,每次從源程序文件OpenFile.java中讀取512個(gè)字節(jié),存儲(chǔ)在緩沖區(qū)buffer中,再將以buffer中的值構(gòu)造的字符串newString(buffer)顯示在屏幕上。程序如下:
- importjava.io.*;
- publicclassOpenFile
- {
- publicstaticvoidmain(Stringargs[])throwsIOException
- {
- try
- {//創(chuàng)建文件輸入流對(duì)象
- FileInputStreamrf=newFileInputStream("OpenFile.java");
- intn=512;
- bytebuffer[]=newbyte[n];
- while((rf.read(buffer,0,n)!=-1)&&(n>0))//讀取輸入流
- {
- System.out.print(newString(buffer));
- }
- System.out.println();
- rf.close();//關(guān)閉輸入流
- }
- catch(IOExceptionioe)
- {
- System.out.println(ioe);
- }
- catch(Exceptione)
- {
- System.out.println(e);
- }
- }
- }
例2Java語(yǔ)言寫(xiě)入文件
本例用System.in.read(buffer)從鍵盤(pán)輸入一行字符,存儲(chǔ)在緩沖區(qū)buffer中,再以FileOutStream的write(buffer)方法,將buffer中內(nèi)容寫(xiě)入文件Write1.txt中,程序如下:
- importjava.io.*;
- publicclassWrite1
- {
- publicstaticvoidmain(Stringargs[])
- {
- try
- {
- System.out.print("Input:");
- intcount,n=512;
- bytebuffer[]=newbyte[n];
- count=System.in.read(buffer);//讀取標(biāo)準(zhǔn)輸入流
- FileOutputStreamwf=newFileOutputStream("Write1.txt");
- //創(chuàng)建文件輸出流對(duì)象
- wf.write(buffer,0,count);//寫(xiě)入輸出流
- wf.close();//關(guān)閉輸出流
- System.out.println("SavetoWrite1.txt!");
- }
- catch(IOExceptionioe)
- {
- System.out.println(ioe);
- }
- catch(Exceptione)
- {
- System.out.println(e);
- }
- }
- }
【編輯推薦】