Java file I/O, java file I
The format of file input and output in Java is not the same as that in C ++. In this article, we will explain how to implement file I/O in Java.
First, determine the object.
java.io.File file = new java.io.File("score.txt");
It is best to determine whether the file exists here to prevent errors when the file content is read later.
Input:
1) Use the java. io. PrintWriter type, that is, java. io. PrintWriter inputFile = new java. io. PrintWriter (file );
2) write data of the String type to the file. You can use inputFile. println (str). Write Data of one row.
3) after writing all the files, you must close the files to take effect, that is, inputFile. close ();
4) The PrintWriter method creates a new file if the file does not exist. If the file already exists, it discards the previous content and reads and writes it again.
5) When file operations occur, throws Exception must be added during declaration.
Output:
1) Use the export type, export outputFile = new export (file). Note that the import java. util. export must be added to the export;
2) When reading the file content, You Need To cyclically judge outputFile. hasNext () until the end of the file;
3) to actually read the file, we also need the method next (), which will read the token separated by the separator. The default separator is space. We can also use useDelimiter (String regex) method to set a new separator;
4) after reading all the data, you need to close the file, outputFile. close ().
5) When file operations occur, throws Exception must be added during declaration.
Package testing;/***** @ author Hadoop **/import java. util. required; // For the following Scannerpublic class TestingFile {/*** main class * @ param args */public static void main (String [] args) throws Exception {// 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 90"; output. println (str); str = "hanmei100"; output. println (str); output. close (); Specify input = new partition (file); while (input. hasNext () {String name = input. next (); // String score = input with space as the separator. next (); System. out. println ("The score of" + name + "is" + score);} input. close ();}}