Содержание
- Java.net.ConnectException: Connection timed out: no further information — Решение
- Connection timed out: no further information – особенности дисфункции
- Как исправить «Java.net.ConnectException: Connection timed out»
- Java.Net.SocketException: Network Is Unreachable
- Possible Reasons and Solution for java.net.SocketException: Network is unreachable in Java
- Minecraft Forums
- java.net.SocketExecption: Network is unreachable
- Ошибка «io.netty.channel.AbstractChannel AnnotatedConnectException» в Minecraft: что делать?
- Чем вызвана ошибка?
- Добавление исключения в Брандмауэр
- Добавление IP-адреса и порта
- Проверка фильтрации портов
Java.net.ConnectException: Connection timed out: no further information — Решение
При попытке подключения к серверу «Майнкрафт» пользователь может столкнуться с сообщением «Java.net.ConnectException: Connection timed out: no further information». Появление данного сообщения обычно сигнализирует о возникновении различного рода сетевых проблем при получении доступа к игровому серверу, из-за чего желание пользователя насладиться игровыми мирами «Майнкрафт» остаётся нереализованным. Ниже я разберу суть данной дисфункции, опишу её причины, а также поясню, как исправить ошибку Java.net.ConnEctexception на вашем ПК.

Connection timed out: no further information – особенности дисфункции
В переводе текст данного сообщения выглядит примерно как «Сетевой сбой Java. Время соединения истекло: дальнейшая информация отсутствует».
Указанная ошибка Java.net.ConnectException обычно возникает во время подключения к серверу игры «Майнкрафт», но также фиксировались спорадические случаи появления данной ошибки при работе других продуктов, использующих «Java» (к примеру, на «Azure notification hub»).
Появление проблемы «Java.net.ConnectException: Connection timed out: no further information» имеет следующие причины:
- Пользователь использует нестабильное сетевое соединение с медленным интернетом;
- На ПК пользователя установлена устаревшая версия «Java»;
- Пользователь пользуется устаревшей версией «Майнкрафт»;
- Наблюдаются сбои в работе игрового сервера, к которому пробует подключиться пользователь (ресурс не доступен, проходят технические работы и др.);
- Антивирус или брандмауэр блокирует подключения к игровому серверу;
- Пользователь использует динамический IP;
- Пользовательский роутер работает некорректно.
Как исправить «Java.net.ConnectException: Connection timed out»
Существуют несколько способов избавиться от ошибки Java.net.ConnectException. Рассмотрим их по порядку:
- Перезагрузите ваш PC. В некоторых случаях данный простой метод позволял решить ошибку java.net.connectexception connection refused;
- Установите на ПК свежую версию «Java». Довольно частой причиной рассматриваемой проблемы является устаревшая версия «Java» на пользовательском ПК. Перейдите в Панель управления, затем в «Программы», там найдите «Java» и кликните на неё. После появления окна её настроек перейдите на вкладку «Update», нажмите там на кнопку «Update Now», и установите в системе требуемые обновления.
Данную процедуру необходимо провести как на вашей машине, так и на машине того пользователя, с которым вы собираетесь играть в «Майнкрафт» по сети;

- Внесите «Майнкрафт» в исключения брандмауэра и антивируса на вашем ПК. Запустите Панель управления, перейдите в «Система и безопасность», там найдите «Брандмауэр Виндовс» и кликните на него. В открывшемся окне настроек брандмауэра слева сверху выберите опцию «Разрешения взаимодействия…».

В открывшемся окне разрешённых для внешнего подключения программ найдите программы с упоминанием «Java», и поставьте им галочки для разрешения подключения (поможет кнопка «Изменить параметры»). Нажимаем на «Ок» для сохранения результата, перезагружаемся и пробуем подключиться к серверу. С антивирусом необходимо проделать аналогичные операции, внеся «Java» и «Майнкрафт» в его исключения;

Установите самую свежую версию программы
Источник
Java.Net.SocketException: Network Is Unreachable
Today, we will discuss the possible reasons and solutions for the java.net.SocketException: Network is unreachable exception while programming in Java.
Possible Reasons and Solution for java.net.SocketException: Network is unreachable in Java
Example Code (Causing an Error):
In this code, we pass the URL and the fileName to the downloadXML() method that reads the .xml file from the specified URL and writes it into the given fileName , which is further saved on our local system.
Though this code example is syntactically and semantically correct but generates the java.net.SocketException: Network is unreachable exception. The error is self-explanatory that tells us the network is not available at the current moment.
The reason causing this error is the connection breakdown. It can happen in Wi-Fi, 3G, or plain internet connection on the machine (computer/laptop).
Whenever we get this error, we must assume that the internet connection is not stable and may be lost from time to time while writing our application.
For instance, this happens with mobiles frequently when we are in the basements or tube, etc. It also happens while using apps on a PC/laptop, but it is less frequent.
The second reason can be incorrect Port and/or HostName . Make sure both are correct.
Additionally, you must remember two more things that can help in error identification.
- First, you will get a java.net.UnknownHostException error if you are completely disconnected from the internet
Usually, the Network is unreachable differs from the Timeout Error . In the Timeout Error , it can’t even find where it should go.
For instance, there can be a difference between having our Wi-Fi card off and no Wi-Fi.
Firstly, perform the usual fiddling with the firewall to ensure that the required port is open. Then, have a look into the network issues that you might have.
Turn off the firewalls and eliminate the obstacles such as routers and complications to make it work in the simplest scenario possible since it is a network-related issue, not code related problem.
Источник
Minecraft Forums
java.net.SocketExecption: Network is unreachable
![]()
I have a server running on a Mac using Craftbukkit. Recently, my computer’s graphics card had to be replaced; and ever since, my friends could not connect to the server. Only I can, using «localhost». When anybody else tries to connect, they get the following error message: «Failed to connect to the server java.net.SocketExecption: Network is unreachable».
Please help! Btw, I tried restarting the server, my wireless connection, and even my computer; yet still nothing works.
Thank you so much!
![]()
- Enderman Ender
- Join Date: 6/3/2011
- Posts: 8,485
- Member Details
This strongly implies that the IP address they are trying to use is bogus.
A port forwarding problem would not manifest itself as a NETWORK unreachable.
This message means that an IP router somewhere is throwing up it’s hands and saying «I have no idea where to send this»
![]()
- Tree Puncher
- Join Date: 1/11/2012
- Posts: 24
- Member Details
This strongly implies that the IP address they are trying to use is bogus.
A port forwarding problem would not manifest itself as a NETWORK unreachable.
This message means that an IP router somewhere is throwing up it’s hands and saying «I have no idea where to send this»
The odd thing is that they have been using the same IP all the time, and only now am I getting this error. I got the IP to use off of IPChicken, and it is the same as always.
![]()
- Tree Puncher
- Join Date: 1/11/2012
- Posts: 24
- Member Details
![]()
- Enderman Ender
- Join Date: 6/3/2011
- Posts: 8,485
- Member Details
that error means the device where your packets are arriving is NOT LISTENING.
So.. either your server is not running, or you are using the wrong IP address to connect with, or your port forwarding is pointed at the wrong IP address.
This is not usually a firewall issue, as they usually just silently eat packets.
![]()
- Tree Puncher
- Join Date: 1/11/2012
- Posts: 24
- Member Details
that error means the device where your packets are arriving is NOT LISTENING.
So.. either your server is not running, or you are using the wrong IP address to connect with, or your port forwarding is pointed at the wrong IP address.
This is not usually a firewall issue, as they usually just silently eat packets.
My server is running, I use the right IP, and I’m pretty sure my port forwarding is pointed at the correct IP address. Whenever I go on Verizon and port forward, it seems to work; yet when I go on canyouseeme.org and test port 25565, it also says connection refused. Man, is this annoying.
EDIT: Other computers in my LAN can connect to my server, but still not outside of my LAN.
Источник
Ошибка «io.netty.channel.AbstractChannel AnnotatedConnectException» в Minecraft: что делать?
Запуск Minecraft может быть прерван ошибкой «io.netty.channel.AbstractChannel AnnotatedConnectException: Connection refused: no further information», которая возникает на этапе подключения к серверу. Узнаем, что предшествует появлению этой ошибки и способы ее исправления.

Чем вызвана ошибка?
Если при запуске Майнкрафт на экране видим ошибку «io.netty.channel.AbstractChannel AnnotatedConnectException», из-за которой игре отказано в подключении, то она может произойти по следующим причинам:
- Подключение к серверу заблокировано брандмауэром Windows. Чтобы этого избежать, нужно добавить в список исключений каталог с игрой и файлы Java.
- Проблема может возникнуть после обновления Minecraft до последней версии, когда в системе используется устаревшая версия Java. В результате это может привести к конфликту с определенными компонентами игры и препятствовать подключению к серверу.
- В фоновом режиме работает программное обеспечение, которое не совместимо с Майнкрафт, и вызывает ошибку при соединении с сервером.
Перед применением решений перезагрузите роутер. Возможно, ошибка возникла из-за ошибочной сетевой конфигурации или повреждения кэша DNS. Отключите кабель питания роутера и подождите 2-3 минуты, прежде чем подключить устройство к электросети. Когда подключение к интернету будет установлено, попробуйте запустить игру.
Кроме того, найдите по запросу в интернете список приложений, которые несовместимы с определенными компонентами Minecraft, и удалите их, если они присутствуют на компьютере.
Добавление исключения в Брандмауэр
Во многих случаях подключение к серверу Minecraft блокируется брандмауэром Windows, что в конечном итоге приводит к ошибке «io.netty.channel.AbstractChannel AnnotatedConnectException». Поэтому попробуйте добавить исключение для некоторых исполняемых файлов из папки Minecraft, которым требуется доступ в интернет.
Разверните меню Пуск и щелкните на значок шестеренки, чтобы открыть системные Параметры, либо просто нажмите Win + I. Перейдите в раздел «Обновления и безопасность».

Откройте вкладку «Безопасность Windows» и перейдите в раздел «Брандмауэр и защита сети».

Выберите опцию «Разрешить работу с приложением через Брандмауэр».
Кликните на кнопку «Изменить параметры» и подтвердите это запрос нажатием на кнопку «Да».

Затем выберите «Разрешить другое приложение» и кликните на кнопку «Обзор». Перейдите в папку Minecraft и выберите исполняемый файл.
Повторите указанные действия еще раз. Перейдите в папку, в которой установлены серверы Minecraft. Откройте папку Maxwell – MinecraftServer. Установите разрешения обоим исполняемым файлам Java внутри этой папки таким же образом.
Теперь найдите в списке все опции «Java Platform SE Binary» и отметьте флажками для частной и публичной сети.
После применения изменений запустите Minecraft и посмотрите, прерывается ли этот процесс ошибкой «io.netty.channel.AbstractChannel AnnotatedConnectException».
Добавление IP-адреса и порта
Если для доступа в интернет используется динамический IP-адрес, он будет меняться каждые пару дней. Поэтому проверьте IP-адрес и порт для игры и добавьте его в лаунчер Minecraft.
Откройте командную строку с помощью поиска Windows, предоставив ей доступ администратора.

В консоли выполните команду ipconfig и запишите IPv4-адрес.

Затем перейдите в папку Minecraft Servers – Maxwell (с набором случайных чисел) – MinecraftServer и откройте текстовый документ «Server Properties».
Найдите в нем и запишите значение строки «Server Port», например, «25565».
Затем запустите Minecraft и перейдите к опции «Play Multiplayer». Выберите сервер и кликните на «Edit» (Редактировать).
Теперь в поле Address укажите IPv4-адрес и номер порта, например, «XXX.XXX.X.X:25565»
Кликните на Done (Готово), затем на кнопку Refresh (Обновить). Проверьте, прерывается ли запуск Minecraft ошибкой.
Проверка фильтрации портов
Иногда проблема может возникнуть в результате случайной фильтрации пользователем требуемых портов. Несмотря на то, что переадресация портов правильно настроена, фильтрация автоматически обнуляет ее, что приводит к указанной ошибке. Проверьте сетевые конфигурации роутера и локальной машины и убедитесь, что фильтрация портов не включена.
Источник
I am trying to download a xml text file from a web server using this method:
static void download (String url , String fileName) throws IOException{
FileWriter xmlWriter;
xmlWriter = new FileWriter(fileName);
System.out.println("URL to download is : " + url);
// here Exception is thrown/////////////////////////////////
BufferedReader inputTxtReader = new BufferedReader
(new BufferedReader(new InputStreamReader(addURL.openStream())));
////////////////////////////////////////////////////////
String str ;
String fileInStr = "";
str = inputTxtReader.readLine();
while (!(str == null) ){///&& !(str.equals("</tv>"))
fileInStr += (str + "rn");
str = inputTxtReader.readLine();
}
xmlWriter.write(fileInStr);
xmlWriter.flush();
xmlWriter.close();
System.out.println("File Downloaded");
}
Sometimes this exception is thrown (where I specified is code):
java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:518)
at java.net.Socket.connect(Socket.java:468)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:389)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:516)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:318)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:788)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:729)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:654)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:977)
at java.net.URL.openStream(URL.java:1009)
at MessagePanel.download(MessagePanel.java:640)
at WelcomThread.run(MainBody2.java:891)
Please guide me
Thank you all.
Buhake Sindi
86.9k28 gold badges167 silver badges224 bronze badges
asked Jul 26, 2011 at 6:51
2
You are facing a connection breakdown. Does this happen in 3G, WiFi or «plain» connection on a computer?
Anyway, you must assume that the connection may be lost from time to time, when writing your app. For example, with mobiles, this happens frequently in the tube, in basements, etc. With PC apps, this is less frequent but occurs sometimes.
A retry can be a good solution. And a clean error message that explains the network is not available at this moment too.
answered Jul 26, 2011 at 7:09
ShlubluShlublu
10.8k4 gold badges52 silver badges69 bronze badges
1
I faced situation of getting java.net.SocketException not sometimes but every time. I’ve added -Djava.net.preferIPv4Stack=true to java command line and my program started to work properly.
answered Nov 18, 2016 at 9:29
![]()
«Network is unreachable» means just that. You’re not connected to a network. It’s something outside of your program. Could be a bad OS setting, NIC, router, etc.
answered Jul 26, 2011 at 7:05
![]()
Ryan StewartRyan Stewart
124k20 gold badges178 silver badges196 bronze badges
1
I haven’t tested with your code so it would be totally different case though, still I’d like to share my experience. (Also this must be too late answer though, I hope this answer still would help somebody in the future)
I recently faced similar experience like you such as some times Network is unreachable, but sometimes not. In short words, what was cause is too small time out. It seems Java throws IOException with stating «Network is unreachable» when the connection fails because of it. It was so misleading (I would expect something like saying «time out») and I spent almost a month to detect it.
Here I found another post about how to set time out.
Alternative to java.net.URL for custom timeout setting
Again, this might not the same case as you got experienced, but somebody for the future.
answered Jan 24, 2018 at 8:07
this just happened to me. None of the answers helped, as the issue was I have recently changed the target host configuration and put incorrect host value there. So it could just be wrong connection details as well.
answered Jan 13, 2021 at 15:19
I faced this error after updating my network adapter configuration (migration to a NIC coupled network by PowerShell commandlet New-NetSwitchTeam). My guess is, that something in the java configuration must be adapted to reflect this change to the java system. But it is unclear where the changes should take place. I am investigating further.
answered Feb 17, 2021 at 17:30
I am trying to download a xml text file from a web server using this method:
static void download (String url , String fileName) throws IOException{
FileWriter xmlWriter;
xmlWriter = new FileWriter(fileName);
System.out.println("URL to download is : " + url);
// here Exception is thrown/////////////////////////////////
BufferedReader inputTxtReader = new BufferedReader
(new BufferedReader(new InputStreamReader(addURL.openStream())));
////////////////////////////////////////////////////////
String str ;
String fileInStr = "";
str = inputTxtReader.readLine();
while (!(str == null) ){///&& !(str.equals("</tv>"))
fileInStr += (str + "rn");
str = inputTxtReader.readLine();
}
xmlWriter.write(fileInStr);
xmlWriter.flush();
xmlWriter.close();
System.out.println("File Downloaded");
}
Sometimes this exception is thrown (where I specified is code):
java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:518)
at java.net.Socket.connect(Socket.java:468)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:389)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:516)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:318)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:788)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:729)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:654)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:977)
at java.net.URL.openStream(URL.java:1009)
at MessagePanel.download(MessagePanel.java:640)
at WelcomThread.run(MainBody2.java:891)
Please guide me
Thank you all.
Buhake Sindi
86.9k28 gold badges167 silver badges224 bronze badges
asked Jul 26, 2011 at 6:51
2
You are facing a connection breakdown. Does this happen in 3G, WiFi or «plain» connection on a computer?
Anyway, you must assume that the connection may be lost from time to time, when writing your app. For example, with mobiles, this happens frequently in the tube, in basements, etc. With PC apps, this is less frequent but occurs sometimes.
A retry can be a good solution. And a clean error message that explains the network is not available at this moment too.
answered Jul 26, 2011 at 7:09
ShlubluShlublu
10.8k4 gold badges52 silver badges69 bronze badges
1
I faced situation of getting java.net.SocketException not sometimes but every time. I’ve added -Djava.net.preferIPv4Stack=true to java command line and my program started to work properly.
answered Nov 18, 2016 at 9:29
![]()
«Network is unreachable» means just that. You’re not connected to a network. It’s something outside of your program. Could be a bad OS setting, NIC, router, etc.
answered Jul 26, 2011 at 7:05
![]()
Ryan StewartRyan Stewart
124k20 gold badges178 silver badges196 bronze badges
1
I haven’t tested with your code so it would be totally different case though, still I’d like to share my experience. (Also this must be too late answer though, I hope this answer still would help somebody in the future)
I recently faced similar experience like you such as some times Network is unreachable, but sometimes not. In short words, what was cause is too small time out. It seems Java throws IOException with stating «Network is unreachable» when the connection fails because of it. It was so misleading (I would expect something like saying «time out») and I spent almost a month to detect it.
Here I found another post about how to set time out.
Alternative to java.net.URL for custom timeout setting
Again, this might not the same case as you got experienced, but somebody for the future.
answered Jan 24, 2018 at 8:07
this just happened to me. None of the answers helped, as the issue was I have recently changed the target host configuration and put incorrect host value there. So it could just be wrong connection details as well.
answered Jan 13, 2021 at 15:19
I faced this error after updating my network adapter configuration (migration to a NIC coupled network by PowerShell commandlet New-NetSwitchTeam). My guess is, that something in the java configuration must be adapted to reflect this change to the java system. But it is unclear where the changes should take place. I am investigating further.
answered Feb 17, 2021 at 17:30
- Печать
Страницы: [1] Вниз
Тема: Network is unreachable (Прочитано 3236 раз)
0 Пользователей и 1 Гость просматривают эту тему.

Dolores
ОС ubuntu-16.04.2-server-amd64
Стоит задача присвоить серверу статический IP
sudo nano /etc/network/interfaces
исправляем вот так:
=====================================================
source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
#auto enp3s0 # комментируем, если сеть не работает - разкомм
#iface enp3s0 inet dhcp # не будет работать - убрать "#"
auto enp3s0
iface enp3s0 inet static
address 192.168.3.200
geteway 192.168.3.1
netmask 255.255.255.0
network 192.168.3.0
broadcast 192.168.3.255
dns-nameservers 192.168.3.1
===============================================================
ping ya.ruполучаем
Network is unreachableЧТО НЕ ТАК? где что исправить, чтоб заработало?
P.S. с динамическим IP пингуется.
« Последнее редактирование: 28 Июля 2017, 18:01:08 от Azure »

fisher74
geteway 192.168.3.1[/quote]

Dolores

koshev
Обратиться к тому, кто выдает серверу адрес, чтобы он его закрепил за сервером?
Ну, как вариант.
А вообще покажите ситуацию при DHCP и статике? А то урывки какие-то, нет целой картины.
ip -s link show dev enp3s0
ip -4 route show dev enp3s0
ip -4 neigh show dev enp3s0
ну и traceroute до хоста в интернете.
во всех случаях.
И уберите пожалуйста
network 192.168.3.0В них нет никакой необходимости при правильно построенной сети, ядро давно (как бы с 2.Х версии) само назначетет ШВ-адрес и адрес сети.
broadcast 192.168.3.255

Dolores
lora@ic-db:~$ ip -s link show dev enp3s0Вот эта команда решает проблему до перезагрузки:
2: enp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether 60:a4:4c:3e:15:b2 brd ff:ff:ff:ff:ff:ff
RX: bytes packets errors dropped overrun mcast
20625 119 0 0 0 23
TX: bytes packets errors dropped carrier collsns
21214 127 0 0 0 0
lora@ic-db:~$ ip -4 route show dev enp3s0
192.168.3.0/24 proto kernel scope link src 192.168.3.200
lora@ic-db:~$ ip -4 neigh show dev enp3s0
192.168.3.34 lladdr 6c:f0:49:e3:5d:9d REACHABLE
192.168.3.40 lladdr 00:1b:fc:8b:2f:1e STALE
192.168.3.1 lladdr ec:43:f6:e2:16:a0 DELAY
lora@ic-db:~$ traceroute ya.ru
traceroute to ya.ru (87.250.250.242), 30 hops max, 60 byte packets
connect: Сеть недоступна
sudo route add –net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1но так быть не должно.

Azure
geteway 192.168.3.1
Исправили?
« Последнее редактирование: 31 Июля 2017, 09:45:33 от Azure »
В Линукс можно сделать ВСЁ что угодно, достаточно знать КАК !
- Печать
Страницы: [1] Вверх
Today, we will discuss the possible reasons and solutions for the java.net.SocketException: Network is unreachable exception while programming in Java.
Possible Reasons and Solution for java.net.SocketException: Network is unreachable in Java
Example Code (Causing an Error):
//import required libraries
import java.io.*;
import java.net.URL;
//Main class
public class Main {
//download method
static void downloadXML (String webUrl, String file) throws IOException{
//create object
FileWriter xmlFileWriter;
xmlFileWriter = new FileWriter(file);
System.out.println("URL used for downloading the file is : " + webUrl);
// this statement throws an Exception
BufferedReader inputTextReader = new BufferedReader (
new BufferedReader(
new InputStreamReader(
new URL(webUrl).openStream())));
//create and initialize variables
String string ;
String fileInString = "";
string = inputTextReader.readLine();
//read file
while (string != null ){
fileInString += (string + "rn");
string = inputTextReader.readLine();
}
//write file
xmlFileWriter.write(fileInString);
xmlFileWriter.flush();
xmlFileWriter.close();
System.out.println("The File is Downloaded");
}//end download() function
//main method
public static void main(String[] args){
try{
downloadXML("https://www.cellml.org/Members/stevens/docs/sample.xml",
"downloadXML.xml");
}catch(IOException exception){
exception.printStackTrace();
}
}//end main
}//end Main class
In this code, we pass the URL and the fileName to the downloadXML() method that reads the .xml file from the specified URL and writes it into the given fileName, which is further saved on our local system.
Though this code example is syntactically and semantically correct but generates the java.net.SocketException: Network is unreachable exception. The error is self-explanatory that tells us the network is not available at the current moment.
The reason causing this error is the connection breakdown. It can happen in Wi-Fi, 3G, or plain internet connection on the machine (computer/laptop).
Whenever we get this error, we must assume that the internet connection is not stable and may be lost from time to time while writing our application.
For instance, this happens with mobiles frequently when we are in the basements or tube, etc. It also happens while using apps on a PC/laptop, but it is less frequent.
The second reason can be incorrect Port and/or HostName. Make sure both are correct.
Additionally, you must remember two more things that can help in error identification.
-
First, you will get a
java.net.UnknownHostExceptionerror if you are completely disconnected from the internet -
Usually, the
Network is unreachablediffers from theTimeout Error. In theTimeout Error, it can’t even find where it should go.For instance, there can be a difference between having our Wi-Fi card off and no Wi-Fi.
Firstly, perform the usual fiddling with the firewall to ensure that the required port is open. Then, have a look into the network issues that you might have.
Turn off the firewalls and eliminate the obstacles such as routers and complications to make it work in the simplest scenario possible since it is a network-related issue, not code related problem.