代码:public int downFile(String serverPath, String clientPath, String fileName){
InputStream inputStream = null;
try{
  String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
  String serverFilePath = serverPath +"/"+ encodeFileName;
//   String gbkFilePath = URLEncoder.encode(serverFilePath, "UTF-8");
FileUtils fileUtils = new FileUtils();
//测试路径和文件是都存在
if(fileUtils.isFileExist(serverFilePath)){
return 1;
}else{
inputStream = getInputStreamFromUrl(serverFilePath);
File resultFile = fileUtils.write2SDFormInput(clientPath, fileName, inputStream);
    if(resultFile == null){
     return -1;
    }
}
}catch (Exception e) {
e.printStackTrace();
return -1;
}finally{
try{
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}

return 0;
}
/**
 * 根据URL的到输入流
 * @param urlStr
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public InputStream getInputStreamFromUrl(String urlStr) 
       throws MalformedURLException, IOException{
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}

解决方案 »

  1.   

    write2SDFormInput方法里面的fileoutputstream的read and wirte 方法的长度参数没加
    public File write2SDFromInput(String path,String fileName,InputStream input){
    File file = null;
    OutputStream output = null;
    try{
    creatSDDir(path);
    file = creatSDFile(path + fileName);
    output = new FileOutputStream(file);
    byte buffer [] = new byte[1024];
    while(true){
    int temp = input.read(buffer,0,buffer.length);
    if(temp == -1){
    break;
    }
    output.write(buffer,0,temp);
    }
    output.flush();
    }
    catch(Exception e){
    e.printStackTrace();
    }
    finally{
    try{
    output.close();
    }
    catch(Exception e){
    e.printStackTrace();
    }
    }
    return file;
    }