/**
* 使用文件通道下载本地文件
* @param source 本地文件路径
* @param target 下载保存路径
*
*/
public static void downLoadFile(String source,String target) throws FileNotFoundException, IOException{
FileInputStream fi=new FileInputStream(source);
FileOutputStream fo=new FileOutputStream(target);
FileChannel ci=fi.getChannel();
FileChannel co=fo.getChannel();
co.transferFrom(co, 0, (new File(source)).length());
co.close();ci.close();fi.close();fo.close();
}
这是从已经存在的文件进行下载。进一步,观察源码,我们可以干脆的用一个输入流来代替当前的本地文件,但是这又引起了新的问题,这个输入流里面的数据长度是多少呢?单位是什么呢?
经过仔细的观察FileChannel的API,我们会发现它的缓冲区设置的长度单位是byte,这样的只有进行将输出结果组成一个字符串,然后返回它byte形式下的长度才可以。