Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The constructor Date(String) is deprecated [duplicate]

Well known deprecated issue causing me a problem. The following line "expiry = new Date(dt);" is the targeted script. To explain in detail I successfully used to

Date expiry = null;
String dt;
if(!(dt=str.nextToken()).equals("null"));
{
  expiry = new Date(dt);
}

Using these lines in the scrips to read the cookies from the file. Yes, the "Date" is deprecated. I have read some solutions but still there are chain of errors while correcting it.

What will be the correct one in the place of "date". Also I provide the full script below

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Reader {

public static void main(String[] args) {
System.setProperty ("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.gmail.com");

try{
    File f = new File("browser.data");
    FileReader fr = new FileReader(f);
    BufferedReader br = new BufferedReader(fr);
String line;

while ((line = br.readLine())!=null){
StringTokenizer str = new StringTokenizer (line, ";");

while (str.hasMoreTokens()) {


    String name = str.nextToken();
    String value = str.nextToken();
    String domain = str.nextToken();
    String path = str.nextToken();

    Date expiry = null;
    String dt;

    if(!(dt=str.nextToken()).equals("null"));
    {
        expiry = new Date(dt);
    }

    boolean isSecure = new Boolean(str.nextToken()).booleanValue();

    Cookie ck = new Cookie (name,value,domain,path,expiry,isSecure);

    driver.manage().addCookie(ck);
    br.close();
}

}
}

catch (Exception ex)
{
    ex.printStackTrace();
}

driver.get("http://gmail.com");



}
}
like image 947
Mukunth Rajendran Avatar asked May 07 '15 09:05

Mukunth Rajendran


1 Answers

The javadoc for the deprecated method usually tells you what the method is replaced by. In this case, the javadoc for Date(String) at https://docs.oracle.com/javase/7/docs/api/java/util/Date.html mentions the following:

Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).

So, if you are using the default date format, you can replace your date construction code with the following;

expiry = java.text.DateFormat.getDateInstance().parse(dt);

If you have a custom date format, you will have to use the java.text.SimpleDateFormat class instead of java.text.DateFormat.

.

like image 86
Priyesh Avatar answered Oct 30 '22 04:10

Priyesh