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("成功建立");
這樣以後,就會進行成功的複製,實現了一個封裝的方法,使文件的複製簡單化。