class cast exception while converting string to date class object? - date

I am trying to convert string into date type object but keep getting class cast exception.I checked everywhere and found the same way as I am using .I have no idea what mistake I am committing.kindly help.
String str;
SimpleDateFormat formatter;
Date date;
str="12/23/2011"
formatter=new SimpleDateFormat("MM/dd/yyyy");
try {
date=(Date)formatter.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

This code works fine with me, maybe you made an error with the imports.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
String str = "12/23/2011";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = null;
try {
date = formatter.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}

Related

How to choose the encode of a file created by SmbFileOutputStream?

I am using a method to create a file in a specific path in a shared folder inside my local net.
public static void stringToArquivoTextoRemoto(String path, String fileName, String content, NtlmPasswordAuthentication auth) {
String absolutePath = path + File.separator + fileName;
try {
jcifs.Config.setProperty("jcifs.smb.client.disablePlainTextPasswords", "false");
SmbFile smbFile = new SmbFile(absolutePath, auth);
SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(smbFile);
smbFileOutputStream.write(content.getBytes());
smbFileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now, I am trying to change the encode from "UTF-8" to "ISO-8859-1".
I already tried to put:
jcifs.Config.setProperty( "jcifs.encoding", "ISO-8859-1" );
But it didn't work.
I found a lot of information about how to change the encode using the FileOutputStream, but I found nothing about this using SmbFileOutputStream.
What do I need to do to choose the encode of a file created by SmbFileOutputStream?
This will solve the issue:
package fileWriting;
import java.io.IOException;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
public class testWriting {
public static void main(String[] args) throws IOException {
String user = "domain;username:password";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://shared/Projects/test.txt";
SmbFile sFile = new SmbFile(path, auth);
try (SmbFileOutputStream sfos = new SmbFileOutputStream(sFile)) {
String v = "Test for file writing!";
byte[] utf = v.getBytes("UTF-8");
byte[] latin1 = new String(utf, "UTF-8").getBytes("ISO-8859-1");
sfos.write(latin1,0,latin1.length );
}
}
}

Need to convert my server timestamp string to another timezone in 'yyyy-MM-dd' format in java

I have an input string like :
billDate="2016-03-16T10:48:59+05:30" (please see the T in between).
Now I want to convert this to another timestamp (America/New_York).
My final result should be like 16 march 2016 or 15th march 2016 depending upon the hour value.
I saw many examples but got no hint how I can convert the above long datetime string to another string for America/New_York.
Can somebody help me on this?
I tried below code but it always gives 16 march for any hour value.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) {
String output = formatDate("2016-03-1611T:27:58+05:30");
System.out.println(output);
}
public static String formatDate(String inputDate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date parsedDate = sdf.parse(inputDate);
return sdf.format(parsedDate);
}
catch (ParseException e) {
// handle exception
}
return null;
}
}
After trying I finally got the code to solve the issue:
The below code works fine:
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class Test {
public static final SimpleDateFormat fDateTime = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
public static void main(String[] args) {
String output = getFormattedDate("2016-03-1611T23:27:58+05:30");
System.out.println(output);
}
public static String getFormattedDate(String inputDate) {
try {
Date dateAfterParsing = fDateTime.parse(inputDate);
fDateTime.setTimeZone(TimeZone.getTimeZone("timeZone"));
return fDateTime.format(dateAfterParsing);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Eclipse Project dependencies dont work when exported

I am currently facing following big problem:
I have a Framework-Project (maven), where a PropertyReader is included (reads "config.properties" in the same package and returns its values):
This is the Framework-Project:
public class PropertyReaderFramework {
private static Properties props;
private static void init(){
String filename = "com/ks/framework/properties/config.properties";
InputStream input = PropertyReaderFramework.class.getClassLoader()
.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
props = null;
} else {
props = new Properties();
}
try {
props.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key){
if(props == null) init();
return props.getProperty(key);
}
public static Properties getProperties(){
if(props == null) init();
return props;
}
}
And my main-project, where I need the information of the properties-file just has one class (for demonstation):
package testmsg;
import com.ks.framework.properties.PropertyReaderFramework;
public class main {
public static void main(String[] args) throws InterruptedException {
try {
String basepath = PropertyReaderFramework.getProperty("remoteFileAccess.script.location");
System.out.println(basepath);
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.sleep(5000);
}
}
}
The funny thing is, that if I execute the main() class in eclipse, it reads the value from the properties correctly.
But when I export it as a runnable JAR, it throws me following error:
Can anyone help me to solve this problem? I cannot figure out why it behaves like that...

Date not getting displayed when used with servlets

In the below program, the last line in the code is showing an error. df and d cannot be resolved. I used the same logic in a normal Java program and I got the output. Can somebody explain the problem in this.
package com.first;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AgeCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
public AgeCalc() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//request parameters
String name1=request.getParameter("name1");
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
}
catch(Exception e){}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
}
}
d and df variables are defined inside try block and are not visible outside of it. Either declare them outside:
DateFormat df = null;
Date d = null;
try {
df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
d=df.parse(dob);
} catch(Exception e){
}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
or better, wrap everything in one huge try block:
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
} catch(Exception e){
}
This is basic Java, not really related to servlets. Also you please do something with the exception, at least:
} catch(Exception e){
e.printStackTrace();
}

Is it possible to extract a large file using Truezip in java?

import java.io.IOException;
import utils.myDate;
import utils.myLog;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TFile;
public class Main
{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Extract(new String("C:/Documents and Settings/mitracomm/My Documents/Downloads/JAR"), new String("D:/Source/Extract Result") , "");
}
private static void Extract(String src, String dst, String incPath)
{
TFile srcFile = new TFile(src + "/" + incPath);
TFile dstFile = new TFile(dst);
try {
TFile.cp_rp(srcFile, dstFile, TArchiveDetector.ALL);
} catch (IOException e) {
myLog.add(myDate.today("yyyyMMdd") + ".log", "error", e.getMessage());
}
}
Will the above code work with a large archive? Also, how can I extract every archive in a directory without having to fill the incPath or specify archives' name? I have tried to do this but I end up with copies of all the archives from origin directory and not extracted files.
The code is principally OK, but I'ld use:
public class Main {
public static void main(String[] args) {
Extract(new String("C:/Documents and Settings/mitracomm/My Documents/Downloads/JAR"), new String("D:/Source/Extract Result") , "");
}
private static void Extract(String src, String dst, String incPath) {
TFile srcFile = new TFile(src, incPath);
TFile dstFile = new TFile(dst);
try {
TFile.cp_rp(srcFile, dstFile, TArchiveDetector.NULL);
} catch (IOException e) {
// I don't like logging for this purpose, but if you must...
myLog.add(myDate.today("yyyyMMdd") + ".log", "error", e.getMessage());
}
}
}
I'm not sure if you really want three arguments for the Extract method, though.
And finally, yes TrueZIP handles ZIP files beyond 4GB size correctly.