基于java文本复制的7种方式总结
程序员文章站
2023-12-13 21:51:04
如下所示:
package copy;
import java.io.bufferedinputstream;
import java.io.buffered...
如下所示:
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 {
// 第一种: 使用filereader和filewrite,一次读取一个字符 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();
// 第二种: 使用filereader和filewrite,一次读取一个字符数组 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();
// 第三种: 使用fileoutputstream和fileinputstream,一次读取一个字节 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();
// 第四种: 使用fileoutputstream和fileinputstream,一次读取一个字节数组 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();
// 第五种: 使用bufferedreader和bufferedwriter,一次读取一行 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();
// 第六种: 使用高效缓冲流,bufferedinputstream和bufferedoutputstream,一次读取一个字节 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();
// 第七种: 使用高效缓冲流,bufferedinputstream和bufferedoutputstream,一次读取一个字节数组 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();
} }
以上这篇基于java文本复制的7种方式总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。