2008年10月18日 星期六

[Java] Readers Vs Writers

常見的Java串流使用範例:

緊記:有開檔,必要有關檔

讀檔 :

import java.io.*;

public class Read{

public static void main(String args[]){

String temp;

try{
FileReader myReader = new FileReader("input.txt");
BufferedReader br = new BufferedReader(myReader);
while((temp = br.readLine()) != null){
System.out.println(temp);
}
}catch(Exception e){}
}
}


建檔->寫檔:

import java.io.*;

public class WriteFile{
public static void main(String[] args) throws Exception{
int a;
try{
File MyFile = new File("MyText.txt");
FileWriter MyFileWriter = new FileWriter(MyFile);
BufferedWriter MyFileBuffer = new BufferedWriter(MyFileWriter);
MyFileBuffer.write("Hello World 1\r\n");
MyFileBuffer.write("Hello World 2");
MyFileBuffer.close();
}catch(Exception e){}
}
}



只要將 FileWriter MyFileWriter = new FileWriter(MyFile);
改成 FileWriter MyFileWriter = new FileWriter(MyFile,true);
代表在檔案的尾部寫入!!

開檔->寫檔(接著原檔尾部寫入):

import java.io.*;

public class WriteFile{
public static void main(String[] args) throws Exception{
int a;
try{
File MyFile = new File("MyText.txt");
FileWriter MyFileWriter = new FileWriter(MyFile,true);
BufferedWriter MyFileBuffer = new BufferedWriter(MyFileWriter);
MyFileBuffer.write("Hello World 1\r\n");
MyFileBuffer.write("Hello World 2\r\n");
MyFileBuffer.close();
}catch(Exception e){}
}
}
[REF]http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String,%20boolean)
[REF]http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

沒有留言:

張貼留言