Several methods of writing to files in Java are Shared

  • 2020-04-01 02:56:07
  • OfStack

FileWritter writes to a file

FileWritter, a stream of characters written to a file. By default, it replaces all existing content with new content, however, when a true (Boolean) value is specified as the second argument to the FileWritter constructor, it retains existing content and appends new content to the end of the file.

1. Replace all existing content with new content.

New FileWriter (file); 2. Retain the existing content and the new content appended to the end of the document.

New FileWriter (file, true);

Append file example
A text file named "javaio-appendfile.txt" and containing the following.

ABC Hello new FileWriter(file,true)


package com.yiibai.file;
 
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
 
public class AppendToFileExample 
{
  public static void main( String[] args )
  { 
   try{
   String data = " This content will append to the end of the file";
 
   File file =new File("javaio-appendfile.txt");
 
   //if file doesnt exists, then create it
   if(!file.exists()){
    file.createNewFile();
   }
 
   //true = append file
   FileWriter fileWritter = new FileWriter(file.getName(),true);
       BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
       bufferWritter.write(data);
       bufferWritter.close();
 
     System.out.println("Done");
 
   }catch(IOException e){
   e.printStackTrace();
   }
  }
}

The results of

Now, the text file "javaio-appendfile.txt" is updated as follows:

ABC Hello This content will append to the end of the file

BufferedWriter writes to a file

BufferedWriter is a character stream class that handles character data. Instead of a byte stream (data converted to bytes), you can write strings, arrays, or characters directly to a file.


package com.yiibai.iofile;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class WriteToFileExample {
 public static void main(String[] args) {
 try {
 
  String content = "This is the content to write into file";
 
  File file = new File("/users/mkyong/filename.txt");
 
  // if file doesnt exists, then create it
  if (!file.exists()) {
  file.createNewFile();
  }
 
  FileWriter fw = new FileWriter(file.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  bw.write(content);
  bw.close();
 
  System.out.println("Done");
 
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
}

Third, the FileOutputStream writes to a file

The file output stream is a byte stream class used to process raw binary data. In order to write data to a file, the data must be converted into bytes and saved to a file. See the full example below.


package com.yiibai.io;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class WriteFileExample {
 public static void main(String[] args) {
 
 FileOutputStream fop = null;
 File file;
 String content = "This is the text content";
 
 try {
 
  file = new File("c:/newfile.txt");
  fop = new FileOutputStream(file);
 
  // if file doesnt exists, then create it
  if (!file.exists()) {
  file.createNewFile();
  }
 
  // get the content in bytes
  byte[] contentInBytes = content.getBytes();
 
  fop.write(contentInBytes);
  fop.flush();
  fop.close();
 
  System.out.println("Done");
 
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  try {
  if (fop != null) {
   fop.close();
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
 }
 }
}

// updated JDK7 for example, USES the new "try resource close" method to handle files easily.


package com.yiibai.io;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class WriteFileExample {
 public static void main(String[] args) {
 
 File file = new File("c:/newfile.txt");
 String content = "This is the text content";
 
 try (FileOutputStream fop = new FileOutputStream(file)) {
 
  // if file doesn't exists, then create it
  if (!file.exists()) {
  file.createNewFile();
  }
 
  // get the content in bytes
  byte[] contentInBytes = content.getBytes();
 
  fop.write(contentInBytes);
  fop.flush();
  fop.close();
 
  System.out.println("Done");
 
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
}

Here are some other comments

Several ways to read and write files for java.io

I. Java abstracts data from these different sources and targets into a data stream.

The input/output capabilities of the Java language are very powerful and flexible.

The IO section of the Java class library is large because it covers a wide range of areas: standard input and output, file operations, data streams on the network, string streams, object streams, zip file streams, and so on.

Here are some ways to read and write files

Ii. InputStream, OutputStream


//Read file (byte stream)
FileInputStream in = new FileInputStream("d:\1.txt");
//Write to the corresponding file
FileOutputStream out = new FileOutputStream("d:\2.txt");
//Read the data
//How many bytes at a time
byte[] bytes = new byte[2048];
//Accept what is read (n represents the relevant data, but in the form of Numbers)
int n = -1;
//Loop fetch data
while ((n = in.read(bytes,0,bytes.length)) != -1) {
  //Convert to string
  String str = new String(bytes,0,n,"UTF-8"); # Here can achieve byte to string conversion, more practical 
  System.out.println(str);
  //Write to related files
  out.write(bytes, 0, n);
  //Clear the cache to write data to the file
  out.flush();
}
//Close the stream
in.close();
out.close();

The BufferedInputStream is used in much the same way as the byte stream, but more efficiently (recommended)


//Read file (cache byte stream)
BufferedInputStream in=new BufferedInputStream(new FileInputStream("d:\1.txt"));
//Write to the corresponding file
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream("d:\2.txt"));
//Read the data
//How many bytes at a time
byte[] bytes = new byte[2048];
//Accept what is read (n represents the relevant data, but in the form of Numbers)
int n = -1;
//Loop fetch data
while ((n = in.read(bytes,0,bytes.length)) != -1) {
  //Convert to string
  String str = new String(bytes,0,n,"UTF-8");
  System.out.println(str);
  //Write to related files
  out.write(bytes, 0, n);
  //Clear the cache and write data to the file
  out.flush();
}
//Close the stream
in.close();
out.close();

InputStreamReader, OutputStreamWriter Use ranges as character conversions


//Read file (byte stream)
InputStreamReader in = new InputStreamReader(new FileInputStream("d:\1.txt"),"UTF-8");
//Write to the corresponding file
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:\2.txt"));
//Read the data
//Loop fetch data
char[] chars = new char[2048];
int len = -1;
while ((len = in.read(chars,0,chars.length)) != -1) {
  System.out.println(len);
  //Write to related files
  out.write(chars,0,len);
  //Clear the cache
  out.flush();
}
//Close the stream
in.close();
out.close();

Five, BufferedReader, BufferedWriter(cache flow, provide readLine method to read a line of text)


FileInputStream fileInputStream = new FileInputStream("d:\1.txt");
FileOutputStream fileOutputStream = new FileOutputStream("d:\2.txt", true);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
//Read file (stream of characters)
BufferedReader in = new BufferedReader(inputStreamReader,"UTF-8"));# This is mainly about Chinese 
//BufferedReader in = new BufferedReader(new FileReader("d:\1.txt")));
//Write to the corresponding file
BufferedWriter out = new BufferedWriter(outputStreamWriter,"UTF-8"));
//BufferedWriter out = new BufferedWriter(new FileWriter("d:\2.txt")) ; 
//Read the data
//Loop fetch data
String str = null;
while ((str = in.readLine()) != null) {
  System.out.println(str);
  //Write to related files
  out.write(str);
  out.newLine();
  //Clear the cache to write data to the file
  out.flush();
}
//Close the stream
in.close();
out.close();

6. Reader, PrintWriter


//Read file (byte stream)
    Reader in = new InputStreamReader(new FileInputStream("d:\1.txt"),"UTF-8");
    //Write to the corresponding file
    PrintWriter out = new PrintWriter(new FileWriter("d:\2.txt"));
    //Read the data
    //Loop fetch data
    byte[] bytes = new byte[1024];
    int len = -1;
    while ((len = in.read()) != -1) {
      System.out.println(len);
      //Write to related files
      out.write(len);
      //Clear the cache
      out.flush();
    }
    //Close the stream
    in.close();
    out.close();

There are only so many basic USES. Of course, each use of reading and writing can be separated. For better use of IO. For reading and writing in the stream, use the BufferedInputStream, BufferedOutputStream


Related articles: