更新時間:2019-08-27 14:31:41 來源:動力節(jié)點 瀏覽2991次
有很多的Java初學(xué)者對于文件復(fù)制的操作總是搞不懂,下面動力節(jié)點java學(xué)院小編將為大家分享Java實現(xiàn)文件復(fù)制的四種方式都是哪些?
實現(xiàn)方式一:使用FileInputStream/FileOutputStream字節(jié)流進(jìn)行文件的復(fù)制操作
private static void streamCopyFile(File srcFile, File desFile) throws IOException {
// 使用字節(jié)流進(jìn)行文件復(fù)制
FileInputStream fi = new FileInputStream(srcFile);
FileOutputStream fo = new FileOutputStream(desFile);
Integer by = 0;
//一次讀取一個字節(jié)
while((by = fi.read()) != -1) {
fo.write(by);
}
fi.close();
fo.close();
}
實現(xiàn)方式二:使用BufferedInputStream/BufferedOutputStream高效字節(jié)流進(jìn)行復(fù)制文件
private static void bufferedStreamCopyFile(File srcFile, File desFile) throws IOException {
// 使用緩沖字節(jié)流進(jìn)行文件復(fù)制
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
byte[] b = new byte[1024];
Integer len = 0;
//一次讀取1024字節(jié)的數(shù)據(jù)
while((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bis.close();
bos.close();
}
實現(xiàn)方式三:使用FileReader/FileWriter字符流進(jìn)行文件復(fù)制。(注意這種方式只能復(fù)制只包含字符的文件,也就意味著你用記事本打開該文件你能夠讀懂)
private static void readerWriterCopyFile(File srcFile, File desFile) throws IOException {
// 使用字符流進(jìn)行文件復(fù)制,注意:字符流只能復(fù)制只含有漢字的文件
FileReader fr = new FileReader(srcFile);
FileWriter fw = new FileWriter(desFile);
Integer by = 0;
while((by = fr.read()) != -1) {
fw.write(by);
}
fr.close();
fw.close();
}
實現(xiàn)方式四:使用BufferedReader/BufferedWriter高效字符流進(jìn)行文件復(fù)制(注意這種方式只能復(fù)制只包含字符的文件,也就意味著你用記事本打開該文件你能夠讀懂)
private static void bufferedReaderWriterCopyFile(File srcFile, File desFile) throws IOException {
// 使用帶緩沖區(qū)的高效字符流進(jìn)行文件復(fù)制
BufferedReader br = new BufferedReader(new FileReader(srcFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(desFile));
char[] c = new char[1024];
Integer len = 0;
while((len = br.read(c)) != -1) {
bw.write(c, 0, len);
}
//方式二
/*String s = null;
while((s = br.readLine()) != null) {
bw.write(s);
bw.newLine();
}*/
br.close();
bw.close();
}
以上就是動力節(jié)點java學(xué)院小編介紹的"Java實現(xiàn)文件復(fù)制的四種方式"的內(nèi)容,分別使用字節(jié)流、高效字節(jié)流、字符流、高效字符流四種方式實現(xiàn)文件復(fù)制的方法,希望以上內(nèi)容對大家有幫助,更多精彩內(nèi)容請關(guān)注動力節(jié)點java學(xué)院官網(wǎng)。
相關(guān)閱讀