Decorating date formats - java

I'm looking for a way to parse a string which would replace some patterns with components of a date that I provide.
Do you know of a standard way to do this?
One usage would be:
parseForDate("fileName%YYYY%MM.csv", new Date()); // returns: filename201301.csv
Best regards

Consider using format:
String filename = String.format("fileName%1$tY%1$tm.csv", new Date());

String filename = "fileName%" + new SimpleDateFormat("yyyy%MM").format(new Date())+".csv"; // returns: filename201301.csv

Related

FileHandler - java.logging.util no carriage return

I'm trying to print log information on file using java.logging.util. This solution is working, but the information from the log doesn't show with the carriage return.
My code:
Main
String url ="opc.tcp://DEV85:53530/OPCUA/SimulationServer";
MyFormatter formatter=new MyFormatter();
fh = new FileHandler("C:/tmp/MyLogFile.log",true);
logger.addHandler(fh);
fh.setFormatter(formatter);
doSomething else()
EndpointDescription[] endpoints = myClient.discoverEndpoints(url);
for(EndpointDescription e: endpoints) {
//System.out.println(e);
logger.info(e.toString());
}
Formatter Class
public class MyFormatter extends Formatter {
// Create a DateFormat to format the logger timestamp.
private static final DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
#Override
public String format(LogRecord record) {
StringBuilder builder = new StringBuilder(1000);
builder.append(df.format(new Date(record.getMillis()))).append(" - ");
builder.append("[").append(record.getSourceClassName()).append(".");
builder.append(record.getSourceMethodName()).append("] - ");
builder.append("[").append(record.getLevel()).append("] - ");
builder.append(formatMessage(record));
builder.append(System.getProperty("line.separator", "\r\n"));
//builder.append("\n");
return builder.toString();
}
}
The output is just on a line. I've found out online some solution, but nothing it's working for me.
One quick nit, the SimpleDateFormat is not thread-safe so you don't what to store it as a object or static reference. Create a new instance each call or use the java.time.format package. Fix this so it is not causing any phantom issues.
This solution is working, but the information from the log doesn't show with the carriage return.
Open the file with a text editor that can show whitespace characters. Your formatter code looks correct. You need to double check that the viewer you are using may be just rendering the text incorrectly (Notepad). Worst case use a FileInputStream and read raw bytes as hex. Should be able to see the hex values for the line separator. Your unit test of just the formatter itself should be able to verify that the line separator is present.
The other issue is that you have to prove that your formatter is being used. You are opening the file for append so it would be possible for other formatters to insert their data in the same file. Consider overriding getHead and getTail to generate a unique id and place that in your formatter for testing. This will show the start and stop of your formatter.
Also the java.util.logging.SimpleFormatter can support this format but it is a global setting and can't be customized for each object.

Java scan a log file and get the time information then calculate the elapsed time

I have a txt file with a line like below:
0 Apr 12 08:42:44.000009 (+0.000009) *** START ***
The information I want to get is:
Apr 12 08:42:44
The current method I'm using use is using a scanner to read this line:
public void getTime() throws IOException {
String time = "";
Scanner scan = new Scanner(location);
String firstLine = scan.nextLine();
String[] splitString = firstLine.split("\\.");
String[] rebootTime = splitString[0].split(" ");
for(int i = 0; i < rebootTime.length; i++) {
if(i != 0) {
time = time + rebootTime[i] + " ";
}
}
System.out.println(time);
}
Is there a smarter way to get the time information?
After I get the time, how do I transfer it to a date format then calculate the duration?
I'm trying to use JAVA 8 Instant with this method, how can I transfer the time value to a Instant type?
If I understand you properly your goal is to extract reboot time from each string of a log file. Using Scanner is ok to my mind. After extracting a line from log file you might as well use regular expressions on it, like this:
String firstLine = scan.nextLine();
Pattern pattern = Pattern.compile("[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
Matcher matcher = pattern.matcher(firstLine);
if (matcher.find()) {
String rebootTime = matcher.group();
}
This regexp is not perfect but it works on your line. You can make it more or less strict.
As to formatting the string to a LocalDateTime, you can use following method:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("MMM dd HH:mm:ss")
.parseDefaulting(ChronoField.YEAR, 1)
.toFormatter();
LocalDateTime date = LocalDateTime.parse(rebootTime, formatter);
So parseDefaulting(ChronoField.YEAR, 1) means that you ignore year in string and set it as 1 in resulting LocalDateTime. After that you can calculate durations using LocalDateTimes.
I like Mongwo's elegant solution.
There are many ways to skin this cat. Other than regular expression, you can simply use a quick-n-dirty one liner, if it is in fixed length and always starting from the fixed index of a string:
String rawStr = "0 Apr 12 08:42:44.000009 (+0.000009) *** START ***";
System.out.println(rawStr.substring(5, 20));
If the file is small enough that you are ok with reading the whole thing, it is generated by another process so that you can guarantee the format, and the line you want is first (which from the question I think all above things should be true), your solution can be as simple as
private SimpleDateFormat format = new SimpleDateFormat("MMM dd HH:mm:ss");
public Date read(String filePath) throws URISyntaxException, IOException, ParseException {
Path fileLocation = Paths.get(filePath);
byte[] data = Files.readAllBytes(fileLocation);
return format.parse(new String(data, 5, 15));
}
If the file is longer, you may want to use a scanner if you dont want to read the whole thing, but imho it is still simplest to use indices to get the part of the string that you want.
If you want a very elegant solution maybe you could use a regex, but I really dont think there is much of a need.
My try here is:-
First let's extract value before dot(".") and then value after double space(" ").
public static void main(String[] args) {
String str = "0 Apr 12 08:42:44.000009 (+0.000009) *** START ***";
String[] str1 = str.split("\\.");
String[] str2 = str1[0].split("\\s{2,}");
System.out.println((str2[1]));
}
To understand \\s{2,} you can look into saved regex.
regex to match 2 spaces

Unable to convert bytes from charset 65535 in to Japanese (5035)

I have a character set conversion issue:
I am updating Japanese Kanji characters in DB2 in iSeries system with the following conversion method:
AS400 sys = new AS400("<host>","username","password");
CharConverter charConv = new CharConverter(5035, sys);
byte[] b = charConv.stringToByteArray(5035, sys, "試験");
AS400Text textConverter = new AS400Text(b.length, 65535,sys);
While retrieving, I use the following code to convert & display:
CharConverter charConv = new CharConverter(5035, sys);
byte[] bytes = charConv.stringToByteArray(5035, sys, dbRemarks);
String s = new String(bytes);
System.out.println("Remarks after conversion to AS400Text :"+s);
But, the system is displaying garbled characters while displaying. Can anybody help me to decode Japanese characters from binary storage?
Well I don't know anything about CharConverter or AS400Text, but code like this is almost always a mistake:
String s = new String(bytes);
That uses the platform default encoding to convert the binary data to text.
Usually storage and retrieval should go through opposite processes - so while you've started with a string and then converted it to bytes, and converted that to an AS400Text object when storing it, I'd expect you to start with an AS400Text object, convert that to a byte array, and then convert that to a String using CharConverter when fetching. The fact that you're calling stringToByteArray in both cases suggests there's something amiss.
(It would also help if you'd tell us what dbRemarks is, and how you've fetched it.)
I do note that having checked some documentation for AS400Text, I've seen this:
Due to recent changes in the behavior of the character conversion routines, this system object is no longer necessary, except when the AS400Text object is to be passed as a parameter on a Toolbox Proxy connection.
There's similar documentation for CharConverter. Are you sure you actually need to go through this at all? Have you tried just storing the string directly and retrieving it directly, without going through intermediate steps?
Thank you Jon Skeet!
Yes. I have committed a mistake, not encoding the string while declaration.
My issue is to get the data stored in DB2, convert it into Japanese and provide for editing in web page. I am getting dbRemarks from the result set. I have missed another thing in my post:
While inserting, I am converting to text like:
String text = (String) textConverter.toObject(b);
PreparedStatement prepareStatementUpdate = connection.prepareStatement(updateSql);
prepareStatementUpdate.setString(1, text);
int count = prepareStatementUpdate.executeUpdate();
I am able to retrieve and display clearly with this code:
String selectSQL = "SELECT remarks FROM empTable WHERE emp_id = ? AND dep_id=? AND join_date='2013-11-15' ";
prepareStatement = connection.prepareStatement(selectSQL);
prepareStatement.setInt(1, 1);
prepareStatement.setString(2, 1);
ResultSet resultSet = prepareStatement.executeQuery();
while ( resultSet.next() ) {
byte[] bytedata = resultSet.getBytes( "remarks" );
AS400Text textConverter2 = new AS400Text(bytedata.length, 5035,sys);
String javaText = (String) textConverter2.toObject(bytedata);
System.out.println("Remarks after conversion to AS400Text :"+javaText);
}
It is working fine with JDBC, but for working with JPA, I need to convert to string for editing in web page or store in table. So, I have tried this way, but could not succeed:
String remarks = resultSet.getString( "remarks" );
byte[] bytedata = remarks.getBytes();
AS400Text textConverter2 = new AS400Text(bytedata.length, 5035,sys);
String javaText = (String) textConverter2.toObject(bytedata);
System.out.println("Remarks after conversion to AS400Text :"+javaText);
Thanks a lot Jon and Buck Calabro !
With your clues, I have succeeded with the following approach:
String remarks = new String(resultSet.getBytes("remarks"),"SJIS");
byte[] byteData = remarks.getBytes("SJIS");
CharConverter charConv = new CharConverter(5035, sys);
String convertedStr = charConv.byteArrayToString(5035, sys, byteData);
I am able to convert from string. I am planning to implement the same with JPA, and started coding.

Truncate a String from a file name

I have previously written a code where I have added a time stamp to a file once it has been save in a directory.
Now I wanna to be able to truncate the time stamp from the file which comes after the extension .txt
note that my time stamp format is:_yyyy-mm-dd.
If you have the date after your extension in the form _yyyy-mm-dd just can use
String strippedFileName = fileName.substring(0, fileName.length() - 11);
or a bit nicer
String dateFormatString = "_yyyy-mm-dd";
String strippedFileName = fileName.substring(0, fileName.length() - dateFormatString.length());
You could also do this:
String trimmed = filename.replaceAll(".{11}$", "");

Get name of an image in java

Is it possible to get the name of an image in java. The image source is a url.
For eg. "http://172.16.2.42/apache_pb.png"
I need the output "apache_pb.png"
String s = "http://172.16.2.42/apache_pb.png";
int index = s.lastIndexOf('/');
String name = s.substring(index+1);
System.out.println(name);
You can use this helper method from the URL class:
String file = new URL("http://172.16.2.42/apache_pb.png").getPath();
Would URL#getFile() do this for you?

Categories