对于文件的基本操作。
public class FileIOTest{
/*读取文件内容*/
public String readContext ( String filePath ){
String result = "" ;
String text = "" ;
BufferedReader br = null ;
try{
br = new BufferedReader( new FileReader( filePath ) ) ;
while ( ( text = br.readLine() ) != null )
result = result + text + "\n\r" ;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
return result ;
}
/*文件中写入内容*/
public void addContext( String filePath ,String text){
BufferedWriter bw = null ;
try{
bw = new BufferedWriter( new FileWriter(filePath) ) ;
bw.write(text);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/*创建一个文件*/
public void createFile ( String filePath ) throws Exception {
File file = new File( filePath ) ;
if ( !file.exists() )
file.createNewFile() ;
}
public static void main (String args[]) throws Exception {
String filePath = "D:\\111.txt" ;
FileIOTest ft = new FileIOTest() ;
ft.createFile( filePath );
ft.addContext(filePath , "男人!\r\n女人!\r\nMAN and woman!");
System.out.println(ft.readContext(filePath)) ;
}
}