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

如何在java中的特定文件夹中保存图像,java,jsp,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

如何在某个目录中保存图像

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();

}
前面的代码不能正常工作。有什么建议吗?

试试这个:

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();
}

只需更换当前使用的第4行即可

OutputStream os = new FileOutputStream(destinationFile); 
对于以下行,所有其他行应保持不变

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

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

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

“它不起作用”一点也不清楚。请准确解释问题所在(文件未创建?引发异常?)。具体点。图像不保存在我的文件夹中我想你可能想先创建文件?而不是编写
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new file(destinationFile))使用此
OutputStream os=new BufferedOutputStream(new FileOutputStream(myDirectory+“\\”+destinationFile))这肯定会起作用。