Java provides the ability to read and write files, through the IO package file, InputStream, outputstream operation, you can manipulate local files, the acquisition of files mainly through the constructor of file, new file (path) to construct.
If the file is not local, how do I get this resource? JAVA.NET provides a network programming tool class that can access network resources through a URL class.
The following provides an implementation of local resource access and network resource access.
/** *
Download local file
* @author Liu Song
* @date 2015-12-30 pm 3:27:02
* @throws Exception
/
private static void Downloadlocalfile () throws exception{
File File = new file ("D:/file/1.txt");
FileInputStream in = new FileInputStream (file);
Defines the path of the output
file Savedir = new file ("D:/file/filecopy");
if (!savedir.exists ()) {
savedir.mkdirs ();//Create multiple directories
}
fileoutputstream os = new FileOutputStream ( savedir+ "/" +file.getname ());
Create buffer
byte buffer[] = new byte[1024];
int len = 0;
Loops read the contents of the input stream into the buffer
while (len = in.read (buffer) > 0) {
os.write (buffer, 0, Len);
}
In.close ();
Os.close ();
}
Download via URLConnection
/** *
Download Network file
* @author Liu Song
* @date 2015-12-30 pm 3:27:19
* @throws Exception
/
private static void Downloadremotefile () throws exception{
url url = new URL ("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/ Superman/img/logo/bd_logo1_31bdc765.png ");
InputStream in = Url.openstream ();
Defines the path of the output
file Savedir = new file ("D:/file/filecopy");
if (!savedir.exists ()) {
savedir.mkdirs ();//Create multiple directories
}
fileoutputstream os = new FileOutputStream ( savedir+ "/" + "download.jpg");
Create buffer
byte buffer[] = new byte[1024];
int len = 0;
Loops read the contents of the input stream into the buffer
while (len = in.read (buffer) > 0) {
os.write (buffer, 0, Len);
}
In.close ();
Os.close ();
}
Download via HttpClient
public static void Main (string[] args) {
httpclient client = new HttpClient ();
GetMethod get = new GetMethod ("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_ 31bdc765.png ");
Client.executemethod (get);
File StoreFile = new file ("D:/file/filecopy");
FileOutputStream output = new FileOutputStream (storefile);
Gets a byte array of network resources and writes to the file
Output.write (Get.getresponsebody ());
Output.close ();
}