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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

怎样用java写一个简单的文件复制程序

發布時間:2024/6/3 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 怎样用java写一个简单的文件复制程序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

怎樣用java寫一個簡單的文件復制程序

代碼來源:https://jingyan.baidu.com/article/c35dbcb0d6f1398916fcbc07.html


package Number;



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Exception;


public class CopyFile {
public static void main(String[] args) throws IOException {
/*在開始前,輸出被拷貝的源文件的大小。*/
File sourceFile =new File(args[0]);
File targetFile =new File(args[1]);

String[] abs = simpleFileName(args);
System.out.println("源文件 copy from\n\t" + args[0] +"\n to\n\t"+ args[1]);
System.out.println("源文件大小:" + sourceFile.length() +"bytes large.\n");


/*首先呢,先判斷傳參是否完整。
如果不夠兩個參數,或者多于兩個參數,提示錯誤。
如果目標文件不存在,創建 空文件繼續復制。*/
if(args.length !=2){
System.out.println("Usage: java copyfile socurceFile targetFile");
System.exit(0);
}else if(!sourceFile.exists()){
System.out.println("socurceFile" + abs[0] + "no exist" );
System.exit(0);
}else if(!targetFile.exists()){
targetFile.createNewFile();
System.out.println("targetFile" + abs[0] + "no exist" );
try {
copyIt(sourceFile,targetFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
copyIt(sourceFile, targetFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


private static void copyIt(File sourceFile, File targetFile) throws Exception {
FileInputStream input = new FileInputStream(sourceFile);
FileOutputStream output = new FileOutputStream(targetFile);
int r;?
int numberofBytesCopied = 0;
while ((r = input.read()) != -1) {
output.write((byte) r);
numberofBytesCopied++;
}
input.close();
output.flush();
output.close();
System.out.println("It is Dome. \nAnd" + numberofBytesCopied + "BytesCopied");

}
/* 獲得文件名稱,即短名。也即路徑下的文件全名(包括文件擴展名)。 */
private static String[] simpleFileName(String[] args) {
String[] abs = new String[2];
if (abs == null || abs.length == 0) {
return null;
}
int index = 0;
for (String str : args) {
if ((str.lastIndexOf("\\") > 0)) {
abs[index++] = str.substring(str.lastIndexOf("\\"));
} else if (str.lastIndexOf("/") > 0) {
abs[index++] = str.substring(str.lastIndexOf("/"));
} // lastIndexOf,注意倒數是大寫的O
}
return abs;
}


}

總結

以上是生活随笔為你收集整理的怎样用java写一个简单的文件复制程序的全部內容,希望文章能夠幫你解決所遇到的問題。

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