文件的文本内容和图片文件在流中都是以字节的形式;
public class Copy {
public static void main(String[] args) throws IOException {String from = "D:/filetest/background.jpg";
String to = "D:/filetest/to.jpg";
new Copy().copyText(from,to); //字节流
String source = "D:/filetest/source.txt";
String target = "D:/filetest/target.txt";
new Copy().copusuper(source,target); //字符流
}/**
* 复制文件from里的内容到文件to里面
* @param from:源文件
* @param to:目标文件
* @throws IOException
*/
public void copyText(String from, String to) throws IOException {
File fileFrom = new File(from);
File fileTo = new File(to);
FileInputStream input = null;
FileOutputStream output = null;
try {//字节流:
//输入流:File--FileInputStream--read;
//输出流:File--FileOutputStream--write;
byte[] buf = new byte[(int)fileFrom.length()];
input = new FileInputStream(fileFrom);
input.read(buf);
output = new FileOutputStream(fileTo,true); //true:把文件内容追加到目标文件内容的后面
output.write(buf);
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
input.close();
output.close();
}
}
}
//高级文件流,以字符形式,传输效率更高,但是有局限性,有些地方只能用字节流;
private void copySuper(String source,String target) throws IOException {
File sourcefile = new File(source);
File targetfile = new File(target);
InputStream ist = null;
InputStreamReader isr = null;
BufferedReader brd = null;
OutputStream ost = null;
OutputStreamWriter osw = null;
BufferedWriter bwt = null;
char[] cbuf = new char[100];
try {/*字符流:将文件读入到高级输入流中:sourceFile/PathName--FileInputStream
--InputStreamReader--BufferReader--read*/
/*从高级输出流中读出数据到指定文件夹:targetfile/PathName--FileOutputStream
--OutputStreamWriter--BufferedWriter--write*/
ist = new FileInputStream(sourcefile);
isr = new InputStreamReader(ist);
brd = new BufferedReader(isr);
brd.read(cbuf);
String str = new String(cbuf);
System.out.println(str);
ost = new FileOutputStream(targetfile,true);
osw = new OutputStreamWriter(ost);
bwt = new BufferedWriter(osw);
bwt.write(cbuf);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
brd.close();
isr.close();
ist.close();
bwt.close();
osw.close();
ost.close();
}
}