Home » Java » Save java to read images on the Internet and to th...

Save java to read images on the Internet and to the local picture file name change

java read the picture on the network and save to local, picture file name unchanged, there is a friend in need can refer to.


needs to download pictures on the Internet in bulk, and found this article. It can download pictures and keep the file name unchanged. It can run directly. The original address is http://wangjunma.iteye.com/blog/1114894


import java.io.DataInputStream;

Import java.io.DataOutputStream;

Import java.io.FileOutputStream;

Import java.net.HttpURLConnection;

Import java.net.URL;

Public class Getpic{

Public Getpic () {

}



Public, static, Boolean, saveUrlAs (String, fileUrl, String, savePath) /*fileUrl network resource address */

{



Try

{

URL url = new URL (fileUrl); / * will pass to the cyber source address, which is assigned to url*/

The usage of fixed format / cyber source contact, so that the back of the in variable URL interception of cyber source input stream */

HttpURLConnection, connection = (HttpURLConnection) url.openConnection ();

DataInputStream, in = new, DataInputStream (connection.getInputStream ());

It can also be used with BufferedOutputStream*/
BufferedInputStream / *
DataOutputStream, out = new, DataOutputStream (new, FileOutputStream (savePath));

/ * parameter savePath, the interception of the pictures stored in the specified local address is assigned to the out output stream of the */
.
Byte[] buffer = new byte[4096];

Int count = 0;

While ((count = in.read (buffer)) > 0) / * input stream in bytes read and write buffer in */

{

Out.write (buffer, 0, count);

}

Out.close (three); / * behind acts to shut the input and output streams and cyber source fixed format */

In.close ();

Connection.disconnect ();

Return true; / * cyber source intercepted and stored in the local true*/
for success


}

Catch (Exception, e)

{

System.out.println (E + fileUrl + savePath);

Return false;

}

}



Public, static, void, main (String[], args)

{

Getpic pic = new (Getpic); / * create an instance of */

String photoUrl =

Http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg ";

The /*photoUrl.substring (photoUrl.lastIndexOf /) method returns the last symbol

* all characters in the 'photoUrl' variable, wrapped in this own symbol */

String fileName = photoUrl.substring (photoUrl.lastIndexOf (` / '));

String filePath = "E:";

/ * call function and parameters */

Boolean flag = pic.saveUrlAs (photoUrl, filePath + fileName);

System.out.println (Run, OK, N, URL, file, Get + Flag);

System.out.println (filePath);

System.out.println (fileName);

}



}



Latest