Search code examples
javaclassimportiphostname

How do I get 'import java.net.*' to work?


I am learning to program in java. I have programmed in other languages. I have tried import java.net.*; at the start of my code file. But it ghosts out. I have looked in my External Libraries directory and it is not there. I found that java.net was deprecated in 201x <-- some recent year. I am using jdk 10. I am using IntelliJ IDE. I have gotten some import statements to work.

I saw on github that they took over hosting oracle classes that were deprecated at Oracle.

I know I have to use the classpath command if I put the .jar or the .zip file containing the class in another directory. I have searched my laptop and i don't have any other .jar or .zip files other than specific other programs I have installed which also don't contain the java.net class (e.g. Aptana Studio 3)

I am using Mac with OS Sierra.

package com.robinhoodcomputer.myfirstprojects;

import java.io.FileReader;  <<-- these import ok
import java.io.*;


import java.net.*;             <<--- these don't import
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;


public class Myreader {
public static void main(String[] args) throws Exception {
    int intVal;
    char myChar;
    String st;
    File file = new File("/java/file");
    BufferedReader br = new BufferedReader(new FileReader(file));
    // FileReader fr = new 
    FileReader("/java/HelloWorld/resources/file.txt");

while ((intVal = br.read()) != -1) {
    myChar = (char) intVal;
    System.out.print(myChar);
    }
myHostName = getLocalHost(); <<-- this doesn't show being available
}
}

I have searched and cannot find any articles that actually do anything but explain how to connect to the class file and that you have to import it in your code. No one talks about getting the java.net class itself. I found one reference to jdk.net in an oracle jdk 10 API specification page.

What am I suppose to use to get the IP address using a hostname in java these days??

thx

P.S. I know this code really doesn't have anything to do with networking, most of it is just reading a file and displaying what's in the file. I wanted to use this code file just to try getting an IP address also. My question is mainly just about making the import statement to work. thx


Solution

  • Your imports are grayed out, since you do not call any method of the imported libraries. As soon as you start using the getLocalHost() method properly, the import will not be grayed out any more. This is a convenience functionality of your IDE it seems.

    getLocalHost() is a method of InetAddress and can't be just called without such an instance.

    Look at this question for how to use this:

    java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?