日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

利用FileReader和FileWriter完成一个文件拷贝功能

發布時間:2024/3/12 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用FileReader和FileWriter完成一个文件拷贝功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目標:

在cmd中可以執行java XXXX d:\1.txt d:\2.txt

完成文件的拷貝命令

package com.ryan.io; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer;public class TestFileReaderAndWriter {public void fileWrite(String destfile) {File f = new File(destfile);String s = "Hello World!!";try {Writer w = new FileWriter(f);w.write(s);w.flush();w.close();} catch (IOException e) {e.printStackTrace();}}public void fileRead(String soucefile) {File f = new File(soucefile);if(f.exists()==false){System.out.println("源文件不存在,請重新輸入");System.exit(0);}char[] c = new char[(int) f.length()];// f.length返回文件的長度分配給字符數組try {//讀取文件/*Reader r = new FileReader(f);int len = r.read(c);System.out.println(new String(c,0,len));*///循環讀取字符Reader r = new FileReader(f);for (int i = 0; i < c.length; i++) {c[i] = (char)r.read(c); // r.read(c)返回的是int型,將int轉為字符型}//System.out.println(new String(c)); //String中的構造函數可以將字符數組轉成字符串} catch (Exception e) {e.printStackTrace();} }public static void main(String[] args) {//利用上面的功能遠成一個文件copy的功能if(args.length != 2){System.out.println("參數不正確,請重新輸入");System.exit(0);}if(args[0].equals(args[1])){System.out.println("不能復制自身!");System.exit(0);}TestFileReaderAndWriter t = new TestFileReaderAndWriter();String soucefile = args[0];String destfile = args[1];t.fileRead(soucefile);t.fileWrite(destfile);System.out.println("文件復制成功");} }
另一種方式,使用字節流,讓文件邊讀邊寫操作

package com.ryan.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream;public class FileCopy {public static void main(String[] args) throws Exception {if(args.length != 2){System.out.println("參數不正確,請重新輸入");System.exit(0);}if(args[0].equals(args[1])){System.out.println("不能復制自身!");System.exit(0);}File src = new File(args[0]); // 找到源文件//判斷源文件是否存在if(src.exists() == false) {System.out.println("源文件不存在");System.exit(0);}else {File dest = new File(args[1]); // 找到目標文件InputStream is = new FileInputStream(src); OutputStream ops = new FileOutputStream(dest);int temp = 0;//temp不等-1表達還沒有讀完while((temp = is.read())!= -1) { // 寫入數據ops.write(temp);}System.out.println("文件復制完成");is.close();ops.close();}} }

總結

以上是生活随笔為你收集整理的利用FileReader和FileWriter完成一个文件拷贝功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。