Java file write and read operations

One: file writing

1: Create a file stream: File f=new File(path);

2: Create a file OutputStream out=new FileOutputStream(f);

3: Write a file: two methods: 1. Call write('') ​​directly, but the encoding format cannot be guaranteed to be correct 2. Create a write class: OutputStreamWriter writer=new OutputStreamWriter(out,"utf-8");

4: Call the writer method to write: writer.append();writer.writer();  

5: Add newline: writer.appden("\r\n");

6: Close the stream

Reading the file:

One: create a file stream f

Two: Create a read stream: InputStreamReader read=new InputStreamReader(f);

Three: Create Stringbuffer to receive

Four: close the stream

import java.io. *;
 
public class fileStreamTest2{
  public static void main(String[] args) throws IOException {
    
    File f = new File("a.txt");
    FileOutputStream fop = new FileOutputStream(f);
    // Build a FileOutputStream object, if the file does not exist, it will be automatically created
    
    OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
    // Build the OutputStreamWriter object, the parameter can specify the encoding, the default is the default encoding of the operating system, gbk on windows
    
    writer.append("Chinese input");
    // write to buffer
    
    writer.append("\r\n");
    // newline
    
    writer.append("English");
    // Refresh the cache and write to the file. If there is no written content below, the direct close will also write
    
    writer.close();
    //Close the write stream and write the buffer content to the file at the same time, so comment out the above
    
    fop.close();
    // Close the output stream and release system resources
 
    FileInputStream fip = new FileInputStream(f);
    // Build the FileInputStream object
    
    InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
    // Build an InputStreamReader object, the encoding is the same as writing
 
    StringBuffer sb = new StringBuffer();
    while (reader.ready()) {
      sb.append((char) reader.read());
      // Convert to char and add it to the StringBuffer object
    }
    System.out.println(sb.toString());
    reader.close();
    // close the read stream
    
    fip.close();
    // Close the input stream and release system resources
 
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324685261&siteId=291194637