This article describes two implementation methods of Java reading and writing data based on character stream form. Share it for your reference, as follows:
The first method: read and write operations one by one character (code comments and free supplements for detailed content)
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){//Single character for reading fw.write(ch);//Single character for writing} fw.close(); fr.close(); }} The second method: customize the 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");//The directory where the project is located 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("Read and write failed"); } } if (fw != null) { try { fw.close(); } catch (IOException e) { System.out.println("Read and write failed"); } } } } } }}For more information about Java algorithms, readers who are interested in this site can view the topics: "Summary of Java Files and Directory Operation Skills", "Tutorial on Java Data Structures and Algorithms", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.