Skip to content

Instantly share code, notes, and snippets.

@Nikolay995
Created April 16, 2018 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nikolay995/da9297e5cc3b288f3de907c993711f98 to your computer and use it in GitHub Desktop.
Save Nikolay995/da9297e5cc3b288f3de907c993711f98 to your computer and use it in GitHub Desktop.
Save content to file using URLConnection and byte buffers
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