Skip to main content

Posts

Showing posts from October, 2019

How to Write to a File in Java

This post shows various options to write to a file in Java. In Java there are two classes FileWriter and FileOutputStream for writing to a file. Out of these two FileWriter is meant for writing streams of characters and FileOutputStream is used for writing streams of raw bytes. In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. So the classes you should use for writing to a file in Java are BufferedWriter and BufferedOutputStream . To see different options available for reading a file in Java, check this post How to Read File in Java Apart from these classes Files class added in Java 7 also provides methods for writing to a file in Java. There is Files.write() method to write bytes to a file. There is also a Files.newBufferedWriter() method which r

How to Read File in Java

In Java there are various ways to read or write a file, in this post we’ll see some of the ways you can read a file in Java. Some of the options you have for reading a file in Java are- Using BufferedReader wrapped around a Reader. See example . Using Scanner class. See example . Using methods in java.nio.file.Files class like readAllLines(), newBufferedReader along with lines() method. See example . To see different options available in Java for writing a file refer this post- How to Write to a File in Java Using BufferedReader to read file in Java Using Java BufferedReader class you can read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. It is therefore advisable to wrap a BufferedReader around

How to Split a String in Java

This post shows how you can split a String in Java using split() method. String you need to split may be delimited using pipe, tab or spaces so let’s see how to use split() method to split such delimited data strings in Java. Note that if you are using any special symbol with in the regular expression then you do need to escape it using escape character (\). Splitting String delimited using pipe(|) symbol - Java code public class SplitString { public static void main(String[] args) { String str = "A001|BOA|Ronda|5000"; String[] data = str.split("\\|"); System.out.println("Name- " + data[2]); } } Output Name- Ronda Splitting data in Java delimited using tab (\t) public class SplitString { public static void main(String[] args) { String str = "A001 BOA Ronda 5000"; String[] data = str.split("\t"); System.out.println("Amount- " + data[3]); } } Output Amount- 5000 Splitting data delimited

Display Time in 24 Hour Format in Java

This post shows how to display time in 24 hour format in Java using SimpleDateFormat and DateTimeFormatter class (Java 8 onward). Pattern for time in 24 hour format In Java pattern for 24 hours are as follows- H - Hour in day (0-23), will return 0-23 for hours. k - Hour in day (1-24), will return 1-24 for hours. As per your requirement for displaying time use the appropriate hour pattern. Using SimpleDateFormat Date date = new Date(); // Pattern SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); System.out.println("Time in 24 Hour format - " + sdf.format(date)); Output Time in 24 Hour format – 16:13:58 Here is another program which shows the difference between using ‘HH’ and ‘kk’ as an hour format. import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class FormatDate { public static void main(String[] args) { Date date = new GregorianCalendar(2019, Calendar.S

Getting Current Date and Time in Java

In this post we’ll see different ways to get current date and time in Java. Options you have are- java.util.Date java.util.Calendar java.time.LocalDate- To get date. java.time.LocalTime- To get time. java.time.LocalDateTime- To get both date and time. java.time.ZonedDateTime – If you want time-zone information too. Out of these classes LocalDate, LocalTime, LocalDateTime and ZonedDateTime are classes in Java 8 new Date and Time API. 1. Getting Date and Time using java.util.Date When you instantiate a Date object, it is initialized so that it represents the date and time at which it was allocated. Date date = new Date(); System.out.println(date); Output Thu Oct 10 16:42:21 IST 2019 Using SimpleDateFormat you can format this date. public class FormatDate { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS"); System.out.println(sdf.format(date));

Convert String to Date in Java

In this post we’ll see how to convert String to Date in Java. For converting Date to String in Java check this post- Convert Date to String in Java Before Java 8, SimpleDateFormat class was the option in Java for converting String to Date. Java 8 onward you can use classes in package java.time which are part of new date and time API for the conversion. We’ll see examples using methods of both of these classes. Table of contents Converting String to Date using SimpleDateFormat Converting String to Date using new Date & Time API Converting String to Date using custom formatter Converting String to Date using SimpleDateFormat You can use parse() method of the Java SimpleDateFormat class that parses text from a string to produce a Date. First thing is to create an instance of SimpleDateFormat passing the date and time pattern for parsing. Then call parse() method passing the date String, method returns parsed Date. ParseException is thrown if unable to par

Convert Date to String in Java

In this post we’ll see how to convert Date to String in Java. For converting String to Date in Java check this post- Convert String to Date in Java Before Java 8, SimpleDateFormat was the class to use for converting Date to String with the specified formatting. Java 8 onward there is another option java.time.format.DateTimeFormatter class that can be used for the conversion. Table of contents Converting Date to String using SimpleDateFormat Converting Date to String using DateTimeFormatter Using DateTimeFormatter.ofLocalizedDate() method Converting Date to String using SimpleDateFormat While creating an instance of SimpleDateFormat you can pass the pattern for formatting. SimpleDateFormat has a format method which takes Date instance as parameter and returns the formatted date (and time) string. Here is an example where current date is converted to String using different date and time formatting patterns. import java.text.SimpleDateFormat; import java.uti

Java Date Difference Program

In this post we’ll see how to calculate date and time difference in Java in terms of Years, months, days and hours, minutes, seconds. To calculate difference between two dates in Java you can use SimpleDateFormat class though using that involves a lot of manual calculation and it doesn’t take time zones, day light saving into account. To mitigate these shortcoming a new Date and Time API is added in Java 8 which provides classes to calculate date and time difference using inbuilt methods and also take into consideration time zones, day light saving and leap years while calculating difference. Table of contents Difference between two dates Using SimpleDateFormat Difference between two dates using Java 8 classes Difference between two dates in terms of years, months, days using Period class Difference between two dates in terms of days, hours, minutes, seconds using Duration class Using both Period and Duration classes to calculate date difference Using