Examples of two implementations of Java for reading and writing data based on character streams

  • 2020-12-13 18:58:54
  • OfStack

This article illustrates two methods of Java to read and write data based on character stream. To share for your reference, the details are as follows:

Method 1: Character-by-character reads and writes (code comments and details are free to supplement)


package IODemo;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileDemo {
 /**
 * @param args
 * @throws IOException 
 */
 public static void main(String[] args) throws IOException {
 FileReader fr=new FileReader("Demo.txt");
 FileWriter fw=new FileWriter("Demo1.txt");
 int ch=0;
 while((ch=fr.read())!=-1){// A single character is read 
 fw.write(ch);// A single character is written 
 }
 fw.close();
 fr.close();
 }
}

Second way: Custom buffer, use read(char buf[]) Method, this method is more efficient


package IODemo;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileDemo2 {
 private static final int BUFFER_SIZE = 1024;
 /**
 * @param args
 */
 public static void main(String[] args) {
 FileReader fr = null;
 FileWriter fw = null;
 try {
 fr = new FileReader("Demo.txt");// Project Directory 
 fw = new FileWriter("Demo2.txt");
 char buf[] = new char[BUFFER_SIZE];
 int len = 0;
 while ((len = fr.read(buf)) != -1) {
 fw.write(buf, 0, len);
 }
 } catch (Exception e) {
 // TODO: handle exception
 } finally {
 if (fr != null) {
 try {
 fr.close();
 } catch (IOException e) {
 System.out.println(" Failure to read and write ");
 }
 }
 if (fw != null) {
 try {
 fw.close();
 } catch (IOException e) {
 System.out.println(" Failure to read and write ");
 }
 }
 }
 }
}

For more information about java algorithm, please refer to Java File and directory Operation Skills Summary, Java Data Structure and Algorithm Tutorial, Java Operation Of DOM Node Skills Summary and Java Cache Operation Skills Summary.

I hope this article has been helpful for java programming.


Related articles: