300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 文件读写操作:把文件a.txt中的内容复制到文件b.txt中

文件读写操作:把文件a.txt中的内容复制到文件b.txt中

时间:2019-07-17 07:17:56

相关推荐

文件读写操作:把文件a.txt中的内容复制到文件b.txt中

文件读写操作:把文件a.txt中的内容复制到文件b.txt中

package com.io.reader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import org.junit.Test;// 文件读写操作:把文件a.txt中的内容复制到文件b.txt中public class ReaderAndWriterTest {// JDK1.7及之后的写法@Testpublic void test02() {try(FileReader fr = new FileReader(new File("a.txt"));FileWriter fw = new FileWriter(new File("b.txt"));) {char[] cbuf = new char[1024];int len;while((len = fr.read(cbuf)) != -1) {fw.write(cbuf, 0, len);}} catch (IOException e) {e.printStackTrace();}}// JDK1.7之前的写法@Testpublic void test01() {// 创建文件输入流对象FileReader fr = null;// 创建文件输出流对象FileWriter fw = null;try {fr = new FileReader(new File("a.txt"));// 在FileWriter的构造器中可以指定文件输出方式是追加模式还是覆盖模式// 如果第二个参数是true表示是追加模式,否则是覆盖模式// 默认是覆盖模式fw = new FileWriter(new File("b.txt"), true);// 读取文件内容char[] cbuf = new char[1024 * 8];int len;while((len = fr.read(cbuf)) != -1) {// 把读取到的内容写出到文件中fw.write(cbuf, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭资源try {if (fw != null) fw.close();} catch (IOException e) {e.printStackTrace();}try {if (fr != null ) fr.close();} catch (IOException e) {e.printStackTrace();}}}}

使用字节流进行文件复制

package com.io.outputstream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.junit.Test;// 使用字节流进行文件复制public class InputStreamAndOutputStreamTest {// JDK1.7的方式@Testpublic void test02() {try(InputStream is = new FileInputStream(new File("e:\\CodeCharts.pdf"));OutputStream os = new FileOutputStream(new File("e:\\CodeCharts_c1.pdf"));) {byte[] b = new byte[1024 * 8];int len;while((len = is.read(b)) != -1) {os.write(b, 0, len);}} catch (Exception e) {e.printStackTrace();}}// JDK1.7之前的方式@Testpublic void test01() {InputStream is = null;OutputStream os = null;try {is = new FileInputStream(new File("e:\\CodeCharts.pdf"));os = new FileOutputStream(new File("e:\\CodeCharts_c.pdf"));byte[] buf = new byte[1024 * 8];int len;while((len = is.read(buf)) != -1) {os.write(buf, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (os != null) os.close();} catch (IOException e) {e.printStackTrace();}try {if (is != null) is.close();} catch (IOException e) {e.printStackTrace();}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。