**
Commonly used streaming classes:
- FileOutputStream / FileInputStream
- ObjectOutputStream / ObjectInputStream
1. Write the serialized object to a file
1. Create a FIleOutputStream
FileOutputStream fileStream = new FileOutputStream("MyGame.ser");
2. Create an ObjectOutputStream
ObjectOutputStream os = new ObjectOutputStream(fileStream);
3. Write object
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
4. Close ObjectOutputStream
os.close();
Second, write the string to a text file
1. Import java.io. *;
import java.io*;
2. The file writing code needs to be included in the try-catch block
3. Instantiate the FileWriter
FileWriter writer = new FileWriter("Foo.txt");
4. Remember to close
writer.close();
Complete code:
import java.io.*;
class WriterAFile{
public static void main(String[] args)
{
try{
FileWiter writer = new FileWriter("Foo.txt");
writer.write("Hello foo!");
writer.close();
}catch(IOException ex)
{
ex.printStackTrace();
}
}
}
Third, the buffer zone
The meaning of the buffer : You can write files through FileWriter, you can also write to BuffereWriter (buffer), and then write to the file through the buffer link FileWriter. It seems that the buffer is a bit redundant, but using FileWriter to write directly is to operate on the disk, and writing to the buffer is to operate on the memory. Each disk operation takes more time than a memory operation. Writing in the buffer first is similar to going to the supermarket and bringing a shopping cart. It is much more convenient to pay when it is full than to pay once for a product.
1. Import java.io. *
import java.io.*;
2. Create the File class
File myFile = new File("MyText.txt");
3. Create the FileReader class
FileReader fileReader = new File(myfile);//参数为上个文件对象
4. Create BufferedReader class
BufferedReader reader = new BufferedReader(fileReader);
5. Use the readLine () method of the BufferedReader class
while((line = reader.readLine())!=null){
System.out.println(line);
}
Note: All the above code should be placed in the try-catch block
Complete code:
import java io.*;
class ReadAFile{
public void main(String[] args){
try{
File myFile = new File("MyText.txt");
FileReader fileReader = new File(myfile);//参数为上个文件对象
BufferedReader reader = new BufferedReader(fileReader);
String line =null;
while((line=reader.readerLine())!=null){
System.out.println(line);
}
reader.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}