The file input and output format in Java is not the same as in C + +, and this article is about how to implement file I/O in Java.
First, determine the file object.
It is best to determine if the file exists and to prevent errors when reading the contents of the file later.
Input:
1) Use Java.io.PrintWriter type, i.e. java.io.PrintWriter inputfile = new Java.io.PrintWriter (file);
2) write to the file string type, you can use INPUTFILE.PRINTLN (str). Writes a row of rows.
3) After the completion of all, need to close the document to be effective, that is, inputfile.close ();
4) PrintWriter method, if the file does not exist will create a new file, if the file already exists, will discard the previous content, re-read and write.
5) The method of file operation, when declaring, need to join throws Exception.
Output:
1) using the Scanner type, Scanner outputfile= new Scanner (file); Note that Scanner needs to add import java.util.Scanner;
2) Read the contents of the file, you need to cycle judgment outputfile.hasnext (), until the end of the file;
3) actually read the file, we also need the method next (), it will read the tokens separated by the token, the default delimiter is a space, we can also use the Usedelimiter (String regex) method to set the new delimiter;
4) After all reading, you need to close the file, Outputfile.close ().
5) The method of file operation, when declaring, need to join throws Exception.
Package testing;/*** * * @author Hadoop * */import Java.util.Scanner; For the back of Scannerpublic class Testingfile {/** * Main class * @param args */public static void MAIN (string[] args) throws Ex ception{//TODO auto-generated method Stubjava.io.File File = new Java.io.File ("Score.txt"); if (!file.exists ()) { System.out.println ("File not Found"); System.exit (0);} Java.io.PrintWriter output = new Java.io.PrintWriter (file); need to throws exceptionstring str = "Lilei"; output.println (str); str = "Hanmei"; output.println (str); OUTP Ut.close (); Scanner input = new Scanner (file); while (Input.hasnext ()) {String name = Input.next (); With a space separator string score = Input.next (); System.out.println ("The score of" + name + "is" + score);} Input.close ();}}
File I/O in Java