java拷貝文件,java拷貝文件並創建目錄

本文目錄一覽:

利用JAVA語言編寫一個 名為copy的程序 實現文件的拷貝功能,應該怎樣做?

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}

java怎麼實現文件拷貝功能

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class CopyFile {

public boolean copy(String file1,String file2) {

File in=new File(file1);

File out=new File(file2);

if(!in.exists()){

System.out.println(in.getAbsolutePath()+”源文件路徑錯誤!!!”);

return false;

}

else {

System.out.println(“源文件路徑”+in.getAbsolutePath());

System.out.println(“目標路徑”+out.getAbsolutePath());

}

if(!out.exists())

out.mkdirs();

File[] file=in.listFiles();

FileInputStream fin=null;

FileOutputStream fout=null;

for(int i=0;ifile.length;i++){

if(file[i].isFile()){

try {

fin=new FileInputStream(file[i]);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(“in.name=”+file[i].getName());

try {

fout=new FileOutputStream(new File(file2+”/”+file[i].getName()));

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(file2);

int c;

byte[] b=new byte[1024*5];

try {

while((c=fin.read(b))!=-1){

fout.write(b, 0, c);

System.out.println(“複製文件中!”);

}

——————————注意

fin.close();

fout.flush();

fout.close();

——————————–

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

——————————-注釋掉

// return true;

}

else copy(file1+”/”+file[i].getName(),file2+”/”+file[i].getName());

}

return false;

}

public static void main(String[] args) {

CopyFile copyFile = new CopyFile();

copyFile.copy(“E:\\study\\opngl”, “E:\\opengl”);

}

}

java 如何拷貝

package czday0017;

import java.io.*;

import java.util.*;

/** IO 工具類 */

public class IO {

/**

* 獲取目錄的全部文件

* @param dir

* @return

*/

public static ListFile listFile(File dir){

return null;

}

/**

* 獲取目錄的全部文件, 指定擴展名的文件

* @param dir

* @return

*/

public static ListFile listFile(

File dir, String ext){

return null;

}

/**

* 遞歸獲取目錄的全部文件

* @param dir

* @return

*/

public static ListFile listAll(

File dir){

return null;

}

/**

* 遞歸獲取目錄的全部文件, 指定擴展名的文件

* @param dir

* @return

*/

public static ListFile listAll(

File dir, String ext){

return null;

}

/**

* 複製文件

*/

public static void cp(String from, String to)

throws IOException {

cp(new File(from), new File(to));

}

/**

* 複製文件

*/

public static void cp(File from, File to)

throws IOException {

cp(new FileInputStream(from),

new FileOutputStream(to));

}

/**

* 複製文件

*/

public static void cp(InputStream in,

OutputStream out)

throws IOException {

//1K byte 的緩衝區!

byte[] buf = new byte[1024];

int count;

while((count=in.read(buf))!=-1){

System.out.println(count);

out.write(buf, 0, count);

}

in.close();

out.close();

}

/**

* 從流中讀取一行文本, 讀取到一行的結束為止

* @param in

* @return 一行文本

*/

public static String readLine(

InputStream in, String charset)

throws IOException{

byte[] buf = {};

int b;

while(true){

b = in.read();

if(b==’\n’ || b==’\r’ || b==-1){//編碼是否是回車換行

break;

}

buf=Arrays.copyOf(buf, buf.length+1);

buf[buf.length-1]=(byte)b;

}

if(buf.length==0 b==-1)

return null;

return new String(buf,charset);

}

/**

* 讀取文件的全部內容到一個byte數組

* 可以緩存一個”小”文件到堆內存中

*/

public static byte[] read(String filename)

throws IOException{

return read(new File(filename));

}

/**

* 讀取文件的全部內容到一個byte數組

* 可以緩存一個”小”文件到堆內存中

*/

public static byte[] read(File file)

throws IOException{

//用RAF打開文件

RandomAccessFile raf =

new RandomAccessFile(file, “r”);

//安裝文件的長度開闢 緩衝區數組(byte數組)

byte[] buf = new byte[(int)raf.length()];

//讀取文件的緩衝區

raf.read(buf);

//關閉文件(RAF)

raf.close();

//返回緩衝區數組引用.

return buf;

}

/**

* 讀取文件的全部內容到一個byte數組

* 可以緩存一個”小”文件到堆內存中

* 如: 文件內容: ABC中 讀取為: {41, 42, 43, d6, d0}

*/

public static byte[] read(InputStream in)

throws IOException{

byte[] ary = new byte[in.available()];

in.read(ary);

in.close();

return ary;

}

/**

* 連接byte 數組的全部內容為字符串,

* 以hex(十六進制)形式連接

* 如: 數組{0x41, 0x42, 0x43, 0xd6, 0xd0}

* 結果: “[41, 42, 43, d6, d0]”

*/

public static String join(byte[] ary){

if(ary==null || ary.length==0)

return “[]”;

StringBuilder buf =

new StringBuilder();

buf.append(“[“).append(

leftPad(Integer.toHexString(ary[0]0xff),’0′,2));

for(int i=1; iary.length; i++){

String hex=Integer.toHexString(ary[i]0xff);

buf.append(“,”).append(leftPad(hex,’0′,2));

}

buf.append(“]”);

return buf.toString();

}

public static String toBinString(byte[] ary){

if(ary==null || ary.length==0)

return “[]”;

StringBuilder buf =

new StringBuilder();

buf.append(“[“).append(

leftPad(Integer.toBinaryString(ary[0]0xff),’0′,8));

for(int i=1; iary.length; i++){

String hex=Integer.toBinaryString(ary[i]0xff);

buf.append(“,”).append(leftPad(hex,’0′,8));

}

buf.append(“]”);

return buf.toString();

}

/**

* 實現leftPad功能, 對字符串實現左填充

* @param str 被填充字符串: 5

* @param ch 填充字符: #

* @param length 填充以後的長度: 8

* @return “#######5”

*/

public static String leftPad(

String str, char ch, int length){

if(str.length() == length){

return str;

}

char[] chs = new char[length];

Arrays.fill(chs, ch);

System.arraycopy(str.toCharArray(), 0, chs,

length – str.length(), str.length());

return new String(chs);

}

/**

* 將text追加到文件 filename的尾部

* 使用系統默認文本編碼

*/

public static void println (

String filename, String text)

throws IOException{

println(new File(filename),text);

}

public static void println(

File file, String text)throws IOException{

OutputStream out = new FileOutputStream(file,true);

println(out, text);

out.close();

}

/**

* 向流中輸出一行字符串, 使用默認編碼

* 不關閉流

* @param out 目標流

* @param text 文本

* @throws IOException

*/

public static void println(

OutputStream out, String text)throws IOException{

out.write(text.getBytes());

out.write(‘\n’);

}

/**

* 向流中輸出一行字符串, 使用指定的編碼

* 不關閉流

* @param out 目標流

* @param text 文本

* @param charset 指定的編碼

* @throws IOException

*/

public static void println(

OutputStream out, String text, String charset)throws IOException{

out.write(text.getBytes(charset));

out.write(‘\n’);

}

/**

* 文件切分

* @param file

* @param size

* @throws IOException

*/

public static void spilt(String file,int size) throws IOException{

if(size=0){

throw new IllegalArgumentException(“幹嗎啊!輸入有誤阿!”);

}

int idx = 0;//文件序號

InputStream in = new BufferedInputStream(new FileInputStream(file));

OutputStream out = new BufferedOutputStream(new FileOutputStream(file+”.”+idx++));

int b;

int count = 0;

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

out.write(b);

count++;

if(count%(size*1024)==0 ){

out.close();

out = new BufferedOutputStream(new FileOutputStream(file+”.”+idx++));

}

}

in.close();

out.close();

}

/**

* 將文件進行連接

* @param filename是一個文件名;如:file.dat.0

*/

public static void join(String file)throws IOException{

String filename = file.substring(0, file.lastIndexOf(“.”));

String num = file.substring(file.lastIndexOf(“.”)+1);

int idx = Integer.parseInt(num);

OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));

File f = new File(filename+”.”+idx++);

while(f.exists()){

InputStream in = new BufferedInputStream(new FileInputStream(f));

cp(in,out);

in.close();

f = new File(filename+”.”+idx++);

}

out.close();

}

/**

* 序列化對象

*/

public static byte[] Serialize(Serializable obj)throws IOException{

return null;

}

public static Object unSerializable(byte[] data)throws IOException{

return null;

}

public static Object clone(Serializable obj)throws IOException{

return unSerializable(Serialize(obj)) ;

}

}

//使用cp工具!

Java怎麼實現文件拷貝

工具/原料

一台配置了java環境的電腦

一款適合自己的開發集成環境,這裡用的是eclipse Kepler

文件拷貝DEMO

1.首先,理清思路,然後我們再動手操作。

拷貝,有源文件,和目的文件。

如果原文件不存在,提示,報錯。

如果目的文件不存在,創建空文件並被覆蓋。

如果目的地址,也即目的路徑不存在,創建路徑。

拷貝,輸入流,輸出流,關閉流。

拷貝前輸出文件大小,計算拷貝大小,比較並核實。輸出。

2.首先呢,先判斷傳參是否完整。

如果不夠兩個參數,或者多於兩個參數,提示錯誤。

如果目標文件不存在,創建 空文件繼續複製。

3.在開始前,輸出被拷貝的源文件的大小。

4.獲得文件名稱,即短名。也即路徑下的文件全名(包括文件擴展名)。

5.拷貝的關鍵,這裡用的簡單的緩衝流。從源文件到目的文件。

number of bytes copied 即是對拷貝長度的累計,直到拷貝完成,輸出。

6.將步驟二中的判斷並拷貝文件的代碼寫在一個main函數中,

執行拷貝,拷貝完成。結果拷貝大小和源文件大小一致,成功。

7.在執行前,記得輸入參數。

如果是使用命令提示符,執行 javac CopyFile.java 之後,

執行 java CopyFile [源文件長名] [目的文件長名]

如果是使用的eclipse,在運行前設置一下運行參數,完成後點擊運行,如下圖。

P.S. 這裏面的所謂「長名」是指完整絕對路徑+文件名+文件類型擴展名

這裡的源文件及目的文件的名稱分別為:

E:/IP_Data.rar 和 D:/testFiles/IP_Data.rar

END

怎樣用java程序實現文件拷貝

通過輸入輸出流解決此問題,具體的可以查看JDK的API,實在不會的話,百度一下應該都有一堆這方面的代碼。

java如何拷貝文件到另一個目錄下

/**

*

複製單個文件

*

@param

oldPath

String

原文件路徑

如:c:/fqf.txt

*

@param

newPath

String

複製後路徑

如:f:/fqf.txt

*

@return

boolean

*/

public

void

copyFile(String

oldPath,

String

newPath)

{

try

{

int

bytesum

=

0;

int

byteread

=

0;

File

oldfile

=

new

File(oldPath);

if

(oldfile.exists())

{

//文件存在時

InputStream

inStream

=

new

FileInputStream(oldPath);

//讀入原文件

FileOutputStream

fs

=

new

FileOutputStream(newPath);

byte[]

buffer

=

new

byte[1444];

int

length;

while

(

(byteread

=

inStream.read(buffer))

!=

-1)

{

bytesum

+=

byteread;

//位元組數

文件大小

System.out.println(bytesum);

fs.write(buffer,

0,

byteread);

}

inStream.close();

}

}

catch

(Exception

e)

{

System.out.println(“複製單個文件操作出錯”);

e.printStackTrace();

}

}

/**

*

複製整個文件夾內容

*

@param

oldPath

String

原文件路徑

如:c:/fqf

*

@param

newPath

String

複製後路徑

如:f:/fqf/ff

*

@return

boolean

*/

public

void

copyFolder(String

oldPath,

String

newPath)

{

try

{

(new

File(newPath)).mkdirs();

//如果文件夾不存在

則建立新文件夾

File

a=new

File(oldPath);

String[]

file=a.list();

File

temp=null;

for

(int

i

=

0;

i

file.length;

i++)

{

if(oldPath.endsWith(File.separator)){

temp=new

File(oldPath+file[i]);

}

else{

temp=new

File(oldPath+File.separator+file[i]);

}

if(temp.isFile()){

FileInputStream

input

=

new

FileInputStream(temp);

FileOutputStream

output

=

new

FileOutputStream(newPath

+

“/”

+

(temp.getName()).toString());

byte[]

b

=

new

byte[1024

*

5];

int

len;

while

(

(len

=

input.read(b))

!=

-1)

{

output.write(b,

0,

len);

}

output.flush();

output.close();

input.close();

}

if(temp.isDirectory()){//如果是子文件夾

copyFolder(oldPath+”/”+file[i],newPath+”/”+file[i]);

}

}

}

catch

(Exception

e)

{

System.out.println(“複製整個文件夾內容操作出錯”);

e.printStackTrace();

}

}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/308529.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-03 14:49
下一篇 2025-01-03 14:49

相關推薦

發表回復

登錄後才能評論