如何在java中的特定文件夹上保存图像

时间:2014-04-19 06:18:35

标签: java jsp

如何在特定目录中保存图像?

private void saveImage(String imageUrl, String destinationFile) throws Exception
{

    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();

}

上述代码无法正常运行。任何建议。?

3 个答案:

答案 0 :(得分:0)

试试这个:

private void saveImage(String imageUrl, String destinationFile) throws Exception
{
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destinationFile)));

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) 
    {
        bos.write(b, 0, length);
    }

    is.close();
    os.close();
}

答案 1 :(得分:0)

在destinationFile本身中指定目录(由saveImage的调用者指定),或者将其添加到saveImage中:

File outFile = new File(myDirectory, destinationFile);
OutputStream os = new FileOutputStream(outFile);

答案 2 :(得分:-1)

只需替换当前

的第4行
OutputStream os = new FileOutputStream(destinationFile); 

使用以下行,所有其他行应保持不变

OutputStream os = new FileOutputStream(new File(destinationFile));