对于文件的基本操作。
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)) ;
}
}
本文提供了一个Java程序示例,展示了如何进行基本的文件输入输出操作,包括读取文件内容、向文件写入内容以及创建文件。这些操作对于理解和实践Java中的文件处理非常有用。

被折叠的 条评论
为什么被折叠?



