JAvaストリームによるファイルとファイル内容の基本操作
1941 ワード
ファイルの基本操作.
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 + "
\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
!\r
MAN and woman!");
System.out.println(ft.readContext(filePath)) ;
}
}