This article is intended to illustrate the basic methods and processes of Java file IO operations as an example.
Source
1 ImportJava.io.*;2 3 Public classMain {4 Final StaticString filename= "Alice.txt";5 //file name6 Public Static voidMain (string[] args) {7 intCount=1;8String dir=system.getproperty ("User.dir");9SYSTEM.OUT.PRINTLN ("The default dir is" +dir);Ten //Show current Path OneFile file=NewFile (dir+FILENAME); A Try { - file.createnewfile (); - //creates a file that has a file with the same name when the CreateNewFile () method is called, and returns false without making a change the}Catch(IOException e) - { - e.printstacktrace (); - } + if(File.exists ()) System.out.println ("The file is exist.")); - if(File.canread ()) System.out.println ("The file can read. Lenth: "+file.length ()); + if(File.canwrite ()) System.out.println ("The file can write"); A //File.delete (); at //File.getpath (); - //some practical methods of file -PrintWriter printwriter=NULL; -BufferedWriter bufferedwriter=NULL; - //do not declare a variable in a try, and the variable will not be accessible in finally - Try{ inPrintwriter=NewPrintWriter (NewFileOutputStream (FILENAME,false)); - //If the file does not exist, a new file is created to //second parameter: Boolean append;true when using "Add Mode", do not create new file, False when creating new file +Printwriter.println (count++ + ":" + "My Name is Alice."); -Printwriter.println (count++ + ":" + "I want to write code."); thePrintwriter.println (count++ + ":" + "I want to having another dance."); * //Write File $ Panax Notoginseng}Catch(IOException e) - { the e.printstacktrace (); + } A finally { the if(printwriter!=NULL) + printwriter.close (); - //Close the stream $ } $BufferedReader bufferedreader=NULL; - Try - { theBufferedreader=NewBufferedReader (NewFileReader (FILENAME)); - String what;Wuyi while(Bufferedreader.ready ()) the{//when there are characters in the stream, read them repeatedly -what=bufferedreader.readline (); Wu System.out.println (what); - } About //Read the file $}Catch(IOException e) - { - e.printstacktrace (); - } A finally { + if(bufferedreader!=NULL) the Try { - bufferedreader.close (); $ //Close the stream the}Catch(IOException e) the { the e.printstacktrace (); the } - } in } the}
Alice.txt file ↑
Console ↑
Java File IO Operation example