写一个方法进行文件的复制

java中实现文件内的复制,须要新建文件的方法:java

File file=new File("wubin.txt");优化

而且没有这个文件,那么须要将这个文件,创造出来:spa

file.createNewFile();input

固然也能够直接在文件流里面直接创造:it

FileInputStream  fis=new FileInputStream(“wubin.txt”);io

意思是在本目录下建立一个wubin.txt的文件,以后创造一个inputstreamreader去获取内容,再经过一个缓冲的bufferreader去作一个速度的优化:class

                      InputStreamReader isr=new InputStreamReader(fis);stream

BufferedReader br=new BufferedReader(isr);file

最后用br的read方法读取。方法

那若是咱们要将读取到的内容给到一个新的文件,就是说创造一个文件,将文件file里面的内容给到新的文件:

                     FileOutputStream fos=new FileOutputStream(“wubin1.txt”);

OutputStreamWriter opw=new OutputStreamWriter(fos);

BufferedWriter bw=new BufferedWriter(opw);

最后用bw的write方法写进去。

问题来了,负责一个文件还能够,若是是多个文件进行负责,很繁琐,且麻烦,

因而本身写了一个copy的方法,来使的这样的操做简便话,定义一个新的类,在该类中,定义一个新的方法copy{}:

class copa{

public void copy(File file,File file1,String s1,String s2) {

           try {

file=new File(s1);

file.createNewFile();

file1=new File(s2);

file1.createNewFile();

} catch (IOException e2) {

e2.printStackTrace();

}

     try {

     

     

FileInputStream fis=new FileInputStream(file);

InputStreamReader isr=new InputStreamReader(fis);

BufferedReader br= new BufferedReader(isr);

//shangmians 读出,下面是写入

FileOutputStream fos=new FileOutputStream(file1);

OutputStreamWriter opw=new OutputStreamWriter(fos);

BufferedWriter bw=new BufferedWriter(opw);

char[] b=new char[100];

try {

br.read(b);

// System.out.println(b);

} catch (IOException e) {

e.printStackTrace();

}

            try {

bw.write(new String(b));

} catch (IOException e1) {

e1.printStackTrace();

}

try {

bw.close();

br.close();

isr.close();

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}

     

}

}

新手进行了一下探索,新建方法copy,定义了两个文件夹file,file1,定义了两个文件名为:s1,s2

在main方法中进行调用:

        File file=new File("");

        File file3=new File("");

       copa copa=new copa();

       copa.copy(file, file3,"jixixin.txt","chengxia.txt");

       System.out.println("成功建立");

这样以后,就会进行成功的复制,实现了一个封装的方法,使文件的复制简单化。

相关文章
相关标签/搜索