As shown below:
package copy;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class FileCopy {public static void main(String[] args) throws IOException { // The first type: Use FileReader and FileWrite to read one character at a time FileReader fr = new FileReader("D://a.txt");FileWriter fw = new FileWriter("D://b.txt");int ch;while((ch = fr.read()) != -1) {fw.write(ch);}fw.close();fr.close(); // The second type: Use FileReader and FileWrite to read one character array at a time FileReader fr = new FileReader("D://a.txt");FileWriter fw = new FileWriter("D://b.txt");char[] chs = new char[1024];int len;while((len = fr.read(chs)) != -1) {fw.write(chs, 0, len);}fw.close();fr.close(); // The third type: Use FileOutputStream and FileInputStream, read one byte at a time FileInputStream fis = new FileInputStream("D://a.txt");FileOutputStream fos = new FileOutputStream("D://b.txt");int ch;while((ch = fis.read()) != -1) {fos.write(ch);}fos.close();fis.close(); // The fourth type: Use FileOutputStream and FileInputStream to read one byte array at a time FileInputStream fis = new FileInputStream("D://a.txt");FileOutputStream fos = new FileOutputStream("D://b.txt");int ch;byte[] by = new byte[1024]; while((ch = fis.read(by)) != -1) {fos.write(by, 0, ch);}fos.close();fis.close(); // The fifth type: Use BufferedReader and BufferedWriter to read one line at a time BufferedReader br = new BufferedReader(new FileReader("D://a.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("D://b.txt"));String line;while((line = br.readLine()) != null) {bw.write(line);bw.newLine();bw.flush();}bw.close();br.close(); // The sixth type: Use efficient buffered streams, BufferedInputStream and BufferedOutputStream, read one byte at a time BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D://a.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D://b.txt"));int ch;while((ch = bis.read()) != -1) {bos.write(ch);}bos.close();bis.close(); // The seventh type: Use efficient buffered streams, BufferedInputStream and BufferedOutputStream, read one byte array at a time BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D://a.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D://b.txt"));int ch;byte[] by = new byte[1024];while((ch = bis.read(by)) != -1) {bos.write(by, 0, ch);}bos.close();bis.close();}}
The above summary of 7 ways of copying Java text is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.