利用JAVA语言编写一个 名为copy的程序 实现文件的拷贝功能,应该怎样做?

利用JAVA语言编写一个 名为copy的程序 实现文件的拷贝功能,应该怎样做?,第1张

import java.io.File\x0d\x0aimport java.io.FileInputStream\x0d\x0aimport java.io.FileNotFoundException\x0d\x0aimport java.io.FileOutputStream\x0d\x0aimport java.io.IOException\x0d\x0apublic class Copy {\x0d\x0a/**\x0d\x0a* @param args\x0d\x0a*/\x0d\x0apublic static void main(String[] args) {\x0d\x0a// TODO Auto-generated method stub\x0d\x0aif(args.length!=2){\x0d\x0aSystem.out.print("没有输入正确数目的参数,程序退出!")\x0d\x0aSystem.exit(0)\x0d\x0a}\x0d\x0aFile fileS = new File("./"+args[0])\x0d\x0aFile fileD = new File("./"+args[1])\x0d\x0aif(fileD.exists())System.out.println("目标文件 "+args[1]+" 已存在!")\x0d\x0abyte[] temp = new byte[50]\x0d\x0aint totalSize = 0\x0d\x0atry {\x0d\x0aFileInputStream fr = new FileInputStream(fileS)\x0d\x0aFileOutputStream fo = new FileOutputStream(fileD)\x0d\x0aint length = 0\x0d\x0awhile((length = fr.read(temp, 0, temp.length)) != -1){\x0d\x0atotalSize += length\x0d\x0afo.write(temp, 0, length)\x0d\x0a}\x0d\x0aSystem.out.println("文件 "+args[0]+" 有 "+totalSize+" 个字节")\x0d\x0aSystem.out.println("复制完成!")\x0d\x0a} catch (FileNotFoundException e) {\x0d\x0a// TODO Auto-generated catch block\x0d\x0ae.printStackTrace()\x0d\x0aSystem.out.println("源文件 "+args[0]+" 不存在!")\x0d\x0a} catch (IOException e) {\x0d\x0a// TODO Auto-generated catch block\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0a}

最简单的io流问题,不用什么高手,

我给你写个方法,参数是2个字符串,第一个写原文件的全路径,第二个写目标文件的全路进。 你试试吧

public void copy(String fromFilePath, String toFilePath) {

try {

FileInputStream fis = new FileInputStream(fromFilePath)

FileOutputStream fos = new FileOutputStream(toFilePath)

byte[] b = new byte[100]

try {

while (fis.read(b) != (-1)) {

fos.write(b)

}

if (fis != null) {

fis.close()

fis = null

}

if (fos != null) {

fos.flush()

fos.close()

fos = null

}

} catch (IOException e) {

System.out.println("io异常")

}

} catch (FileNotFoundException e) {

System.out.println("源文件不存在")

}

public static void main(String[] args) {

//自己把路径补齐,别忘了!!!!!!!!!!!!!!!!

String fromFilePath=" " // 源文件的全路径。 比方"d://myphoto//nihao.mp3"

String toFilePath=" "//目标文件的全路劲。 如果不存在会自动建立,如存在则在文件尾继续添加

new CopyTest().copy(fromFilePath, toFilePath)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8160448.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-14
下一篇 2023-04-14

发表评论

登录后才能评论

评论列表(0条)

保存