古詩詞大全網 - 成語解釋 - java 中簡述使用流進行讀寫文本文件的步驟?

java 中簡述使用流進行讀寫文本文件的步驟?

壹、Java IO學習基礎之讀寫文本文件

Java的IO操作都是基於流進行操作的,為了提高讀寫效率壹般需要進行緩沖。

簡單的示例程序如下:

/**

* 讀出1.txt中的內容,寫入2.txt中

*

*/

import java.io.*;

public class ReadWriteFile{

public static void main(String[] args){

try{

File read = new File("c:\\1.txt");

File write = new File("c:\\2.txt");

BufferedReader br = new BufferedReader(

new FileReader(read));

BufferedWriter bw = new BufferedWriter(

new FileWriter(write));

String temp = null;

temp = br.readLine();

while(temp != null){

//寫文件

bw.write(temp + "\r\n"); //只適用Windows系統

//繼續讀文件

temp = br.readLine();

}

bw.close();

br.close();

}catch(FileNotFoundException e){ //文件未找到

System.out.println (e);

}catch(IOException e){

System.out.println (e);

}

}

}

以上是壹個比較簡單的基礎示例。本文上下兩部分都是從網上摘抄,合並在壹起,方便下自己以後查找。

二、Java IO學習筆記+代碼

文件對象的生成和文件的創建

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:10

*

* 文件對象的生成和文件的創建

*/

package study.iostudy;

import java.io.*;

public class GenerateFile

{

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject1 = new File("oneFirst.txt");

File fileObject2 = new File("d:\\mydir", "firstFile.txt");

System.out.println(fileObject2);

try

{

dirObject.mkdir();

}catch(SecurityException e)

{

e.printStackTrace();

}

try

{

fileObject2.createNewFile();

fileObject1.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

文件名的處理

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:29

*

* 文件名的處理

*/

package study.iostudy;

import java.io.*;

/*

* 文件名的處理

* String getName(); 獲得文件的名稱,不包含文件所在的路徑。

* String getPath(); 獲得文件的路徑。

* String getAbsolutePath(); 獲得文件的絕對路徑。

* String getParent(); 獲得文件的上壹級目錄的名稱。

* String renameTo(File newName); 按參數中給定的完整路徑更改當前的文件名。

* int compareTo(File pathName); 按照字典順序比較兩個文件對象的路徑。

* boolean isAbsolute(); 測試文件對象的路徑是不是絕對路徑。

*/

public class ProcesserFileName

{

public static void main(String[] args)

{

File fileObject1 = new File("d:\\mydir\\firstFile.txt");

File fileObject2 = new File("d:\\firstFile.txt");

boolean pathAbsolute = fileObject1.isAbsolute();

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("There are some information of fileObject1's file name:");

System.out.println("fileObject1: " + fileObject1);

System.out.println("fileObject2: " + fileObject2);

System.out.println("file name: " + fileObject1.getName());

System.out.println("file path: " + fileObject1.getPath());

System.out.println("file absolute path: " + fileObject1.getAbsolutePath());

System.out.println("file's parent directory: " + fileObject1.getParent());

System.out.println("file's absoulte path: " + pathAbsolute);

int sameName = fileObject1.compareTo(fileObject2);

System.out.println("fileObject1 compare to fileObject2: " + sameName);

fileObject1.renameTo(fileObject2);

System.out.println("file's new name: " + fileObject1.getName());

}

}

測試和設置文件屬性

/*

* SetterFileAttribute.java

*

* Created on 2006年8月22日, 下午3:51

*

* 測試和設置文件屬性

*/

package study.iostudy;

import java.io.*;

public class SetterFileAttribute

{

/*

* File類中提供的有關文件屬性測試方面的方法有以下幾種:

* boolean exists(); 測試當前文件對象指示的文件是否存在。

* boolean isFile(); 測試當前文件對象是不是文件。

* boolean isDirectory(); 測試當前文件對象是不是目錄。

* boolean canRead(); 測試當前文件對象是否可讀。

* boolean canWrite(); 測試當前文件對象是否可寫。

* boolean setReadOnly(); 將當前文件對象設置為只讀。

* long length(); 獲得當前文件對象的長度。

*/

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject = new File("d:\\mydir\\firstFile.txt");

try

{

dirObject.mkdir();

fileObject.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("there are some information about property of file object:");

System.out.println("file object : " + fileObject);

System.out.println("file exist? " + fileObject.exists());

System.out.println("Is a file? " + fileObject.isFile());

System.out.println("Is a directory?" + fileObject.isDirectory());

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

long fileLen = fileObject.length();

System.out.println("file length: " +fileLen);

boolean fileRead = fileObject.setReadOnly();

System.out.println(fileRead);

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

}

}

文件操作方法

/*

* FileOperation.java

*

* Created on 2006年8月22日, 下午4:25

*

* 文件操作方法

*/

package study.iostudy;

import java.io.*;

/*

* 有關文件操作方面的方法有如下幾種:

* boolean createNewFile(); 根據當前的文件對象創建壹個新的文件。

* boolean mkdir(); 根據當前的文件對象生成壹目錄,也就是指定路徑下的文件夾。

* boolean mkdirs(); 也是根據當前的文件對象生成壹個目錄,

* 不同的地方在於該方法即使創建目錄失敗,

* 也會成功參數中指定的所有父目錄。

* boolean delete(); 刪除當前的文件。

* void deleteOnExit(); 當前Java虛擬機終止時刪除當前的文件。

* String list(); 列出當前目錄下的文件。

*/

public class FileOperation

* 找出壹個目錄下所有的文件

package study.iostudy;

import java.io.*;

public class SearchFile

{

public static void main(String[] args)

{

File dirObject = new File("D:\\aa");

Filter1 filterObj1 = new Filter1("HTML");

Filter2 filterObj2 = new Filter2("Applet");

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("list HTML files in directory: " + dirObject);

String[] filesObj1 = dirObject.list(filterObj1);

for (int i = 0; i < filesObj1.length; i++)

{

File fileObject = new File(dirObject, filesObj1[i]);

System.out.println(((fileObject.isFile())

? "HTML file: " : "sub directory: ") + fileObject);

}

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

String[] filesObj2 = dirObject.list(filterObj2);

for (int i = 0; i < filesObj2.length; i++)

{

File fileObject = new File(dirObject, filesObj2[i]);

System.out.println(((fileObject.isFile())

? "htm file: " : "sub directory: ") + fileObject);

}

}

}

class Filter1 implements FilenameFilter

{

String fileExtent;

Filter1(String extentObj)

{

fileExtent = extentObj;

}

public boolean accept(File dir, String name)

{

return name.endsWith("." + fileExtent);

}

}

class Filter2 implements FilenameFilter

{

String fileName;

Filter2(String fileName)

{

this.fileName = fileName;

字符流處理

* ProcesserCharacterStream.java

* 字符流處理

*

* java.io包中加入了專門用於字符流處理的類,這些類都是Reader和Writer類的子類,

* Reader和Writer是兩個抽象類,只提供了壹系列用於字符流處理的接口,不能生成這

* 兩個類的實例。

* java.io包中用於字符流處理的最基本的類是InputStreamReader和OutputStreamWriter,

* 用來在字節流和字符流之間作為中介。

*

* 下面是InputStreamReader類和OutputStreamWriter類的常用方法:

*

* public InputStreamReader(InputStream in)

* 根據當前平臺缺省的編碼規範,基於字節流in生成壹個輸入字符流。

* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException

* 按照參數sysCode指定的編碼規範,基於字節流in構造輸入字符流,如果不支持參數sysCode中指定的編碼規範,就會產生異常。

* public OutputStreamWriter(OutputStream out)

* 根據當前平臺缺省的編碼規範,基於字節流out生成壹個輸入字符流。

* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException

* 按照參數sysCode指定的編碼規範,基於字節流out構造輸入字符流,如果不支持參數sysCode中指定的編碼規範,就會產生異常。

* public String getEncoding()

* 獲得當前字符流使用的編碼方式。

* public void close() throws IOException

* 用於關閉流。

* public int read() throws IOException

* 用於讀取壹個字符。

* public int read(char[] cbuf, int off, int len)

* 用於讀取len個字符到數組cbuf的索引off處。

* public void write(char[] cbuf, int off, int len) throws IOException

* 將字符數組cbuf中從索引off處開始的len個字符寫入輸出流。

* public void write(int c) throws IOException

* 將單個字符寫入輸入流。

* public void write(String str, int off, int len) throws IOException

* 將字符串str中從索引off位置開始的ltn個字符寫入輸出流。

*

* 此外,為了提高字符流處理的效率,在Java語言中,引入了BufferedReader和BufferWriter類,這兩個類對字符流進行塊處理。

* 兩個類的常用方法如下:

* public BufferedReader(Reader in)

* 用於基於普通字符輸入流in生成相應的緩沖流。

* public BufferedReader(Reader in, int bufSize)

* 用於基於普通字符輸入流in生成相應的緩沖流,緩沖區大小為參數bufSize指定。

* public BufferedWriter(Writer out)

* 用於基於普通字符輸入流out生成相應的緩沖流。

* public BufferedWriter(Writer out, int bufSize)

* 用於基於普通字符輸入流out生在相應緩沖流,緩沖流大小為參數bufSize指定。

* public String readLine() throws IOException

* 用於從輸入流中讀取壹行字符。

* public void newLine() throws IOException

* 用於向字符輸入流中寫入壹行結束標記,值得註意的是,該標記不是簡單的換行符"\n",而是系統定義的屬性line.separator。

在上面的程序中,我們首先聲明了FileInputStream類對象inStream和

* FileOutputStream類的對象outStream,接著聲明了BufferInputStream

* 類對象bufObj、BufferedOutputStream類對象bufOutObj、

* DataInputStream類對象dataInObj以及PushbackInputStream類對象pushObj,

* 在try代碼塊中對上面這些對象進行初始化,程序的目的是通過BufferedInputStream

* 類對象bufInObj和BufferedOutputStream類對象bufOutObj將secondFile.txt

* 文件中內容輸出到屏幕,並將該文件的內容寫入thirdFile.txt文件中,值得註意的是,

* 將secondFile.txt文件中的內容輸出之前,程序中使用

* "System.out.println(dataInObj.readBoolean());" 語句根據readBoolean()結果

* 輸出了true,而secondFile.txt文件開始內容為“Modify”,和壹個字符為M,

* 因此輸出的文件內容沒有“M”字符,thirdFile.txt文件中也比secondFile.txt

* 文件少第壹個字符“M”。隨後,通過PushbackInputStream類對象pushObj讀取

* thirdFile.txt文件中的內容,輸出讀到的字符,當讀到的不是字符,輸出回車,將字符

* 數組pushByte寫回到thirdFile.txt文件中,也就是“ok”寫回文件中。

* 對象串行化

* 對象通過寫出描述自己狀態的數值來記錄自己,這個過程叫做對象串行化。對象的壽命通

* 常是隨著生成該對象的程序的終止而終止,在有些情況下,需要將對象的狀態保存下來,然後

* 在必要的時候將對象恢復,值得註意的是,如果變量是另壹個對象的引用,則引用的對象也要

* 串行化,串行化是壹個遞歸的過程,可能會涉及到壹個復雜樹結構的串行化,比如包括原有對

* 象,對象的對象等。

* 在java.io包中,接口Serializable是實現對象串行化的工具,只有實現了Serializable

* 的對象才可以被串行化。Serializable接口中沒有任何的方法,當壹個類聲明實現Seriali-

* zable接口時,只是表明該類遵循串行化協議,而不需要實現任何特殊的方法。

* 在進行對象串行化時,需要註意將串行化的對象和輸入、輸出流聯系起來,首先通過對

* 象輸出流將對象狀態保存下來,然後通過對象輸入流將對象狀態恢復。