Created
April 16, 2018 16:56
-
-
Save Nikolay995/da9297e5cc3b288f3de907c993711f98 to your computer and use it in GitHub Desktop.
Save content to file using URLConnection and byte buffers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InetWork { | |
public static void saveToFile(String address, File folder) { | |
try { | |
URL url = new URL(address); //установка соединения | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //возможность доступа | |
InputStream is = connection.getInputStream(); //поток | |
int n = address.lastIndexOf("/"); //после последнего слеша будет имя файла | |
String fileName = address.substring(n + 1); //записываем сюда имя файла | |
File file = new File(folder, fileName); //сохраняем в каталоге фолдер с именем файлНейм | |
OutputStream os = new FileOutputStream(file); | |
byte[] array = new byte[1024 * 1024]; //буфферный массив | |
int readByte = 0; //сколько байт уже прочитано | |
while ((readByte = is.read(array)) > 0) { | |
os.write(array, 0, readByte); | |
} | |
is.close(); | |
os.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment