Tuesday, April 28, 2020

7 Examples to Read File into a byte array in Java

Java programmers often face scenarios in real-world programming, where they need to load data from a file into a byte array, it could be text or binary file. One example is to convert the contents of a file into String for display. Unfortunately, Java’s File class, which is used to represent both files and directories, doesn’t have a method say toByteArray(). It only holds path and allows you to perform certain operations like opening and closing file, but doesn’t allow you to directly convert File to a byte array. Anyway, no need to worry as there are several other ways to read File into a byte array and you will learn those in this Java file tutorial.

Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java Exam Prep, Java Prep

If you are a fan of Apache commons and Google Guava like me, then you may already familiar with one-liner code, which can quickly read a file into a byte array; if not, then this is the right time to explore those API.

In this tutorial, we are going to see 7 different examples to read File to a byte array, some by using third party libraries, and others by using JDK 6 and JDK 7 core Java libs.

Depending upon your choice, you can use any of the following methods to convert file data into bytes. One thing to keep in mind is what you are doing with byte array; if you are creating String from a byte array, then beware with character encoding. You may need to find out correct character encoding by reading metadata information like Content-Type of HTML pages and of XML documents.

While reading XML documents, it’s a bad idea to first read an XML file and store it in a String. Instead, it’s better to pass InputStream to XML parsers, and they will figure out the encoding themselves correctly.

One more thing to note is that you cannot read file larger than 2GB into a single byte array, you need multiple byte arrays for that. This limitation comes from the fact that the array index in Java is of int type, whose maximum value is 2147483647, roughly equivalent to 2GB.

Btw, I am expecting that you are familiar with basic Java Programing and Java API in general.

7 ways to read a file into a byte array in Java


Without wasting any more of your time, here are all the seven ways to load a file into a byte array in Java:

1) Using Apache Commons IOUtils


This is one of the easiest ways to read a file data into a byte array, provided you don’t hate third-party libraries. It’s productive because you don’t need to code it from scratch, worrying about exception handling, etc.

byte[] filedata = IOUtils.toByteArray(new FileInputStream("info.xml"));

The  IOUtils.toByteArray(InputStream input) Gets the contents of an InputStream as a byte[]. This method also buffers the input internally, so there is no need to use a BufferedInputStream, but it’s not null-safe. It throws  NullPointerException if the input is null.

2) Using Apache Commons FileUtils


The FileUtils class from org.apache.commons.io package provides a general file manipulation facility like writing to a file or reading from a file.  This method is used to read the contents of a file into a byte array, and the good thing about this is that the file is always closed.

byte[] data = FileUtils.readFileToByteArray(new File("info.xml"));

3) Using FileInputStream and JDK


This is the classic way of reading the file’s content into a byte array. Don’t forget to close the stream once done.  Here is the code to read a file into a byte array using FileInputStream class in Java:

public static byte[] readFile(String file) throws IOException {
 
   File f = new File(file);
 
   // work only for 2GB file, because array index can only up to Integer.MAX
 
   byte[] buffer = new byte[(int)f.length()];
 
   FileInputStream is = new FileInputStream(file);
 
   is.read(buffer);
 
   is.close();
 
   return  buffer;
 
}

In production, use  finally block to close streams to release file descriptors.

4) Using Google Guava Files class


Files class of Google Guava provides utility methods for working with files, like converting files to a byte array, to string with specified charset, copy, move, etc. Files.toByteArray() method reads all bytes from a file into a byte array and throws IllegalArgumentException if the file size is bigger than the largest possible byte array (2^31 – 1).

byte[] bytes = Files.toByteArray(new File("info.xml"));

This approach of reading files content into byte array has several advantages, first of all, you don’t need to reinvent the wheel. Second, it uses NIO for reading a file, which will perform better than stream IO. You also don’t need to worry about handling exceptions and closing streams, as Guava does for you.

5) Using Guava’s ByteStreams utility


Guava’s ByteStreams class provides utility methods for working with byte arrays and I/O streams. The toByteArray() takes an InputStream and reads all bytes into a byte array but it does not close the stream, so you need to close it by yourself.

This is one reason, I don’t prefer this method, the Java 7 example we saw in the last section takes care of closing streams.

byte[] g2Bytes = ByteStreams.toByteArray(new FileInputStream("info.xml"));

By the way, If you are using Java in-memory constraint environment like Android, then consider using obfuscator like proguard to remove unused classes from third-party libraries. For example, Guava by default adds more than 2MB to an APK. But with Proguard it comes down to about 250KB

6) Using JDK 7 NIO Files and Path


If you are using Java 7, then this is the best way to convert File into a byte array. It allows you to read all bytes from a file and capture them in a byte array. All you need to know is the path of the file.

Here is the code sample to read a file in Java 7:

Path path = Paths.get("info.xml");
byte[] raw = java.nio.file.Files.readAllBytes(path);

The biggest advantage of this approach is that it doesn’t require any third-party libraries. It’s also a static method, which makes it very convenient. It also ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Something Java has been lacking from the first edition.

By the way, this method is only intended for simple use where it is convenient to read all bytes into a byte array. It is not intended for reading large files and throws OutOfMemoryError, if an array of the required size cannot be allocated, for example, the file is larger than 2GB.

By the way, if you only have File object and not Path then you can also use File.toPath() to convert File to Path in JDK 1.7.

Oracle Java Tutorial and Material, Oracle Java Certifications, Oracle Java Exam Prep, Java Prep

7) Using RandomAccessFile in Java


You can also use RandomeAccessFile to convert File into an array of bytes as shown below, though you can also use read(byte[]) method, it’s better to use readFully.

RandomAccessFile f = new RandomAccessFile("info.xml", "rw");
 
byte[] b = new byte[(int)f.length()];
 
f.readFully(b);

Also, note that RandomAccessFile is not thread-safe. So, synchronization may be needed in some cases.

Last thing, some of the code here is not production quality, as they are not handling exceptions properly. In real-world, all file handling code must close streams in finally block to release file descriptor associated with that, failure to do so may result in you java.io.IOException: Too many open files error.

Sometimes you can expect libraries like Apache commons IO for closing streams properly, as seen below from a code snippet from FileUtils class of Apache Commons IO, the closeQuietly() methods close a stream ignoring nulls and exceptions.

        InputStream in = null;
 
        try {
 
            in = openInputStream(file);
 
            return IOUtils.toByteArray(in, file.length());
 
        } finally {
 
            IOUtils.closeQuietly(in);
 
        }
 
    }

but it’s not always true, as Google Guava’s ByteStreams.toByteArray method doesn’t close the stream. It’s better to check documentation before using a particular method in production code. In general, it’s better to use JDK API if available and that’s why a good knowledge of JDK goes a long way to becoming an expert Java programmer.

Java Program to Read A file into Byte Array in Java


Here is our complete Java program to read a file into a byte array in Java. This combines all the 6 approaches I have shown above. You can copy-paste this example and run in your favorite IDE like Eclipse, NetBeans, or IntelliJIDEA.

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.nio.charset.Charset; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import org.apache.commons.io.FileUtils; 
import org.apache.commons.io.IOUtils; 
import com.google.common.io.ByteStreams; 
import com.google.common.io.Files; 
   
/** 
 * 
 */
  
public class Testing {
  
    public static void main(String args[]) throws IOException {
  
        // Example 1: Using Apache Commons IOUtils to read file into byte array
  
        byte[] filedata = IOUtils.toByteArray(new FileInputStream("info.xml"));
  
        String str = new String(filedata, "UTF-8");
  
        System.out.println("File to byte[] using IOUtils.toByteArray \n" + str);
  
        // Example 2: Reading File to byte[] using FileUtils class
  
        byte[] data = FileUtils.readFileToByteArray(new File("info.xml"));
  
        System.out.println("Converting File to byte[] using FileUtils \n"
  
                + new String(data, StandardCharsets.UTF_8));
  
        // Example 3: Using FileInputStream and JDK
  
        byte[] contents = readFile("info.xml");
  
        System.out.printf("File to byte[] Java without thirdpaty library %n %s %n",
  
                new String(contents, StandardCharsets.UTF_8));
  
        // Example 4: Using Google Guava, uses NIO
  
        byte[] bytes = Files.toByteArray(new File("info.xml"));
  
        System.out.printf("Convert File to byte array Using Google %n %s %n",
  
                new String(bytes, "UTF-8"));
  
        // Example 5:
  
        byte[] g2Bytes = ByteStreams.toByteArray(new FileInputStream("info.xml"));
  
        System.out.println("File to byte[] using Guvava \n " + new String(g2Bytes, "UTF-8"));
  
        // Example 6: Using JDK 7 NIO Path and Files class
  
        Path path = Paths.get("info.xml");
  
        byte[] raw = java.nio.file.Files.readAllBytes(path);
  
        System.out.println("Read File to byte[] in JDK 7 \n " + new String(raw, "UTF-8"));
  
        //Example 7: Using RandomAccessFile in Java
  
        RandomAccessFile f = new RandomAccessFile("info.xml", "rw");
  
        byte[] b = new byte[(int) f.length()];
  
        f.readFully(b);
  
        System.out.println("Load File to byte[] in Java using RandomAccessFile \n "
  
                + new String(b, "UTF-8"));
  
    }
  
    /*
  
     * Reading File into byte array using JDK classes only
  
     */
  
    public static byte[] readFile(String file) throws IOException {
  
        File f = new File(file);
  
        // work only for 2GB file, because array index can only upto Integer.MAX
  
        byte[] buffer = new byte[(int) f.length()];
  
        FileInputStream is = new FileInputStream(file);
  
        is.read(buffer);
  
        is.close();
  
        return buffer;
  
    }
  
}
  
Output:
  
File to byte[] using IOUtils.toByteArray 
Name: Société Générale 
Headquarters: Île-de-France, France 
Converting File to byte[] using FileUtils 
Name: Société Générale 
Headquarters: Île-de-France, France 
File to byte[] Java without thirdpaty library
  
 Name: Société Générale 
Headquarters: Île-de-France, France
  
Convert File to byte array Using Google 
 Name: Société Générale
  
Headquarters: Île-de-France, France 
File to byte[] using Guvava
  
 Name: Société Générale 
Headquarters: Île-de-France, France
  
Read File to byte[] in JDK 7 
 Name: Société Générale
  
Headquarters: Île-de-France, France
  
Load File to byte[] in Java using RandomAccessFile 
 Name: Société Générale
  
Headquarters: Île-de-France, France

That’s all on this tutorial of 7ways to read a file into a byte array in Java. Now you know that there are multiple ways to read the file in Java, some by using third party libraries like Apache Commons IO, Google Guava, Apache MINA, and others by just employing standard JDK file input-output classes. Depending upon your requirement, you can use any of these solutions to read file data into a byte in Java. Keep an eye on character encoding if you are converting byte array to String.

Also, remember that array in Java can only hold a limited amount of data as it’s length cannot exceed Integer.MAX_VALUE (2GB). So you cannot convert a large file into a single-byte array, though you can read large data using input stream, you need to process them in chunks or using multiple byte arrays.

Source: javacodegeeks.com

Monday, April 27, 2020

JVM

How to process images and videos within Java JVM

Java JVM, Oracle Java Tutorial and Material, Oracle Java Guides, Java Exam Prep

Processing of images – let alone videos – within the Java JVM has always been a challenging task. ImageIO classes have come a long way since JDK7 – together with the usual SDK bugs – not always giving you what you expect (bad image quality, not always supporting all types of JPEG standards, …). At the end of the line you are better off with open source libraries specifically written for image processing, like ImageMagick and GraphicsMagick. These libraries are also what we use in our ImageServer Across Module to generate thumbnails and variants for images, PDFs, …

Recently we were involved in a project where we had to display and play audio/video files which had been uploaded by a customer. The page also showed some metadata from the media asset and files would be rejected after upload (e.g. if the bitrate or other metadata was not adequate). In short we had to parse metadata for all kinds of audio and video assets and then render this media file to the customer. We aren’t talking about a Netflix streaming platform here, just some basic audio/video streaming.

We looked for libraries that could parse video files (in this case we were talking MXF files) to extract the metadata. There are libraries like Netflix Photon (https://github.com/Netflix/photon/releases) and https://github.com/jforaci/mxf-reader. But would you really want to parse and read files in the JVM? The short answer is no, you don’t want all this crud in your Java memory.

So what are the options?

Metadata parsing


We looked at ffmpeg and MediaInfo for this.

If you have ever converted your personal (S)VCD,DVD disks to MKV (Matroska container) – or AVI, MPEG back in the days – you surely noticed that ffmpeg is the defacto tool for converting/parsing media files.

MediaInfo is a tool which was suggested by the customer and provides structured metadata probing from media files.

The parser we wrote supports ffmpeg and Mediainfo for flexibility and maps the JSON from these tools onto the same data structure. Both give similar outputs

ffmpeg probe

$ ffprobe -show_format -show_streams audiocheck.net_polarity_guitarOK.wav -print_format json -loglevel 0
{
    "streams": [
        {
            "index": 0,
            "codec_name": "pcm_s16le",
            "codec_long_name": "PCM signed 16-bit little-endian",
            "codec_type": "audio",
            "codec_time_base": "1/44100",
            "codec_tag_string": "[1][0][0][0]",
            "codec_tag": "0x0001",
            "sample_fmt": "s16",
            "sample_rate": "44100",
            "channels": 2,
            "bits_per_sample": 16,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/44100",
            "duration_ts": 224041,
            "duration": "5.080295",
            "bit_rate": "1411200",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            }
        }
    ],
    "format": {
        "filename": "audiocheck.net_polarity_guitarOK.wav",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "wav",
        "format_long_name": "WAV / WAVE (Waveform Audio)",
        "duration": "5.080295",
        "size": "896208",
        "bit_rate": "1411269",
        "probe_score": 99
    }
}
$ mediainfo --output=JSON audiocheck.net_polarity_guitarOK.wav
{
"media": {
"@ref": "audiocheck.net_polarity_guitarOK.wav",
"track": [
{
"@type": "General",
"AudioCount": "1",
"FileExtension": "wav",
"Format": "Wave",
"FileSize": "896208",
"Duration": "5.080",
"OverallBitRate_Mode": "CBR",
"OverallBitRate": "1411351",
"StreamSize": "44",
"File_Modified_Date": "UTC 2020-03-03 12:02:30",
"File_Modified_Date_Local": "2020-03-03 13:02:30"
},
{
"@type": "Audio",
"Format": "PCM",
"Format_Settings_Endianness": "Little",
"Format_Settings_Sign": "Signed",
"CodecID": "1",
"Duration": "5.080",
"BitRate_Mode": "CBR",
"BitRate": "1411200",
"Channels": "2",
"SamplingRate": "44100",
"SamplingCount": "224028",
"BitDepth": "16",
"StreamSize": "896164",
"StreamSize_Proportion": "0.99995"
}
]
}
}

Note that if you are using a stock Debian install, you need to install the .deb packages from https://mediaarea.net/en/MediaInfo/Download/Debian – otherwise you will be stuck with a (very) old version which has no JSON output.

Wrapping these outputs to a common data structure was more than enough to do our metadata processing checks and store some of the metadata for display purposes (e.g. the duration and the format of the media file).

Thumbnail generation


For thumbnail generation, there were two requirements. An audio file would have to generate a waveform. A video file would have to generate a good thumbnail for that video.

Based on the metadata above, you can quickly differentiate if the uploaded media file is an audio file or a video file (a video file has a video stream/track).

Both follow another track for thumbnail generation.

Audio thumbnail generation and audio playing


To display the waveform on overview pages, we simply use ffmpeg to generate a waveform with the following command

$ ffmpeg -y -i inputfile -filter_complex "showwavespic=colors=#007bff:split_channels=1" -frames:v 1 -c:v png -loglevel -8

This would generate a waveform in PNG format and split the different audio channels in the waveform. After this image is generated, we upload it to our Across ImageServer.

On the details page of the audio asset, we use WaveSurfer (https://wavesurfer-js.org/) to play the audio file and render the audio channels – nothing special there.

Video thumbnail generation and video playing


To display a thumbnail on overview pages, we can use the ffmpeg thumbnail filter

$ ffmpeg -i inputFile -vf "thumbnail" -frames:v 1

This filter is quite good at guestimating a good thumbnail picture. You can do more fancy things like

$ ffmpeg -ss 3 -i inputFile -vf "select=gt(scene\,0.5)" -frames:v 5 -vsync vfr out%02d.png

Which would generate 5 thumbnail frames, skipping 3 seconds from the start (these might be credits) and grabbing the frames where “scene changes” are bigger than 50%.

In the end the customer decided the last second frame would be the best for their purpose since that frame usually contains a closing packshot from the commercial video.

Since the videos are 25fps the command we ended up with was the following (where 89 is the total number of frames – 26). Yes, 26 … because ffmpeg does zero-based counting of the frames.

$ ffmpeg -i inputFile -vf "select=gte(n\,89)" -frames:v 1

The generated thumbnail is then uploaded in ImageServer and that’s that. Now … to play the video file …

Well, MXF files are not supported by video players on the web, the best bet was to transcode this video container format to MP4 (which is the most compatible cross browser format these days).

Luckely, ffmpeg comes to the rescue, though it can be challenging to find the right command which generates an MP4 that plays in most of the browsers.

$ ffmpeg -y -i inputFile -vcodec libx264 -pix_fmt yuv420p -profile:v baseline -level 3 transcodedFile

This command generates an MP4 file with a baseline profile and a YUV420P color encoding scheme. This baseline profile and color scheme makes sure it displays properly on Safari (for Mac).

The transcoded file is stored using the Across FileRepositoryModule in a backing store (Azure BLOB storage in this case but it also support AWS S3 or a Local store).

Now … to really play the video file …

We need a video player for the web to achieve this. The most common library there is videojs (https://videojs.com/) which is easy to setup and quite customizable, enough for our purposes.

Just providing the <video> tag with the correct url immediately yielded results in Firefox and Chrome, however Safari was stubborn to play the file.

Safari tries to be a bit special – as always with Apple things – by adding Range Headers to the HTTP request. This is to avoid sending all bytes from the video file in one go over the wire.

Instead the HTTP Range headers specify which byte ranges need to be fetched.

Saturday, April 25, 2020

How To Validate Phone Numbers in Java (Regular Expression + Google libphonenumber)

Oracle Java Study Materials, Oracle Java Certifications, Oracle Guides, Oracle Java Exam Prep

A quick guide to how to validate phone numbers in java for different countries such as the USA, IN. Example programs with Regular Expression and Google libphonenumber API.

1. Introduction


In this tutorial, We’ll learn how to validate phone numbers in java. This is to validate mainly the USA and India country phone numbers but after seeing the example you can develop the validation rules for other countries.

This is a common requirement to verify mobile numbers as we do validation for email address validation but java does not have built-in capability to provide such methods. But, We can achieve this with the help of regular expression and google api with libphonenumber.

Let us jump into writing example programs.

2. Regular Expression


Regular expression implementation is a bit tricky because phone number has lots of formats with different extensions.

For example, here are some of the common ways of writing phone numbers for the
USA.

1234567890
123-456-7890
123-456-7890 x1234
123-456-7890 ext1234
(123)-456-7890
123.456.7890
123 456 7890

India:

9123124123

Phone Number Validation with Regular Expression

package com.java.w3schools.blog.java.program.to.libphonenumber;
 
public class PhoneValidationRegularExpression {
 
 public static void main(String[] args) {
 
  System.out.println("Validation for 1234567890 : " + validatePhoneNumber("1234567890"));
  System.out.println("Validation for 1234 567 890 : " + validatePhoneNumber("1234 567 890")); 
  System.out.println("Validation for 123 456 7890 : " + validatePhoneNumber("123 456 7890"));
  System.out.println("Validation for 123-567-8905 : " + validatePhoneNumber("123-567-8905"));
  System.out.println("Validation for 9866767545 : " + validatePhoneNumber("9866767545"));
  System.out.println("Validation for 123-456-7890 ext9876 : " + validatePhoneNumber("123-456-7890 ext9876"));
 
 }
 
 private static boolean validatePhoneNumber(String phoneNumber) {
  // validate phone numbers of format "1234567890"
  if (phoneNumber.matches("\\d{10}"))
   return true;
  // validating phone number with -, . or spaces
  else if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
   return true;
  // validating phone number with extension length from 3 to 5
  else if (phoneNumber.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
   return true;
  // validating phone number where area code is in braces ()
  else if (phoneNumber.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
   return true;
  // Validation for India numbers
  else if (phoneNumber.matches("\\d{4}[-\\.\\s]\\d{3}[-\\.\\s]\\d{3}"))
   return true;
  else if (phoneNumber.matches("\\(\\d{5}\\)-\\d{3}-\\d{3}"))
   return true;
 
  else if (phoneNumber.matches("\\(\\d{4}\\)-\\d{3}-\\d{3}"))
   return true;
  // return false if nothing matches the input
  else
   return false;
 
 }
}

Output:

Validation for 1234567890 : true
Validation for 1234 567 890 : true
Validation for 123 456 7890 : true
Validation for 123-567-8905 : true
Validation for 9866767545 : true
Validation for 123-456-7890 ext9876 : true

3. Google libphonenumber Example


If you go with the regex approach, you need to do lots of testing to cover all the corner cases. But, if we have some api that provides this functionality with proper testing that would be good to use in our application.

libphonenumber API is provided by Google as an opensource library that provides the functionalities such as parsing, formatting, validating and storing international phone numbers.

This API is optimized for running on smartphones and also used by the Android framework.

The main advantage of this API is that you can format or validate and parse any country or region mobile numbers.

Class PhoneNumberUtil is a utility for international phone numbers. Functionality includes formatting, parsing, and validation.

package com.java.w3schools.blog.java.program.to.libphonenumber;
 
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
 
public class PhoneValidationWIthGooglelibphonenumberAPI {
 
 public static void main(String[] args) throws NumberParseException {
 
  PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
 
  PhoneNumber phoneNumber = numberUtil.parse("9866123456", "IN");
 
  boolean isValid = numberUtil.isValidNumber(phoneNumber);
 
  System.out.println("Checking given phone number is vaid : " + isValid);
 }
 
}

Output:

Checking given phone number is vaid : true

Another Example To Validate USA OR India Phone numbers:


package com.java.w3schools.blog.java.program.to.libphonenumber;
 
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
 
public class PhoneValidationWIthGooglelibphonenumberAPI {
 
 public static void main(String[] args) throws NumberParseException {
 
  System.out.println("USA phone number validations: ");
  String[] usPhoneNumbers = { "(541) 754-3010", "+1-541-754-3010", "1-541-754-3010", "001-541-754-3010",
    "191 541 754 3010" };
  validatePhoneNumber(usPhoneNumbers, "US");
 
  System.out.println("\nindia phone number validations: ");
  String[] indiaPhoneNumbers = { "+91 7503907302", "9702522865", "+91–8477812345", "+91 9999999999",
    "+91 9688 123 456", "+9688 123 456" };
  validatePhoneNumber(indiaPhoneNumbers, "IN");
 
 }
 
 private static void validatePhoneNumber(String[] phoneNumbers, String region) throws NumberParseException {
 
  PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
 
  for (String number : phoneNumbers) {
 
   PhoneNumber phoneNumber = numberUtil.parse(number, region);
 
   boolean isValid = numberUtil.isValidNumber(phoneNumber);
 
   if (isValid) {
    System.out.println(number + " is a valid number.");
   } else {
    System.out.println(number + " is a not valid number.");
   }
 
  }
 
 }
}

Output:

USA phone number validations: 
(541) 754-3010 is a valid number.
+1-541-754-3010 is a valid number.
1-541-754-3010 is a valid number.
001-541-754-3010 is a not valid number.
191 541 754 3010 is a not valid number.
 
india phone number validations: 
+91 7503907302 is a valid number.
9702522865 is a valid number.
+91–8477812345 is a valid number.
+91 9999999999 is a valid number.
+91 9688 123 456 is a valid number.
+9688 123 456 is a not valid number.


4. PhoneNumberType


This api supports all the below types of numbers.

FIXED_LINE  
FIXED_LINE_OR_MOBILE  
MOBILE  
PAGER  
PERSONAL_NUMBER  
PREMIUM_RATE  
SHARED_COST  
TOLL_FREE  
UAN  
UNKNOWN  
VOICEMAIL  
VOIP

Friday, April 24, 2020

How to check if a File exists in Java with Example

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Certification

Hello guys,  if you are working in Java for a couple of years then you have come across a scenario where you need to check if a file exists or not. This is often required while writing defensive code that writes or read from a file. While there is a method to check if a file exists in Java or not, it's not so straight forward to use because it returns true if a given path represents a file or a directory. Yes, I am talking about the File.exists() method of java.io package. This method is the key method to solve this problem but you need to keep in mind that it returns true if a given path exists and its either file or directory. If your requirement is not just to check if the path is valid but also it represents a file and you have permission to read the file then you also need to ensure that it's not a directory.

If you are looking for a code example to check if a file exists in Java or not then you have come to the right place. In this article, I will show you a Java program and we will see how to check if a File exists or not.

Its common requirement to first check if a file with input pathname exists or not and if there is no File than create a new file but before that, you need to do this check. Earlier, I have shared how to check if a file is empty or not and today, I will share whether a file exists or not.

While File.exists() looks alright to solve this problem there is another gem which many Java developers don't know, yes, I am talking about File.isFile() method which not only checks if a file exists but also ensures that its a file. This is actually a better way to check if a file exists in Java or not.

Java Example to check if File exists in Java or not


Following is my sample Java program to check if a File exists in directory or not. The absolute or relative path of a file is provided as input to program and it will tell you if that file exists in a file system or not.

import java.io.File;

/**
  * Simple Java program to check if a file exits or not.
  * While checking whether a file exist or not it's also important
  * to check if a path represent a File or Directory
  * because exists() method of File class return true if path points
  * to either directory or File in Java.
 
  */
public class FileTest{ 
 
    public static void main(String args[]) {

        // name of File to be check for existence
        String path = "C:/sample.txt"; //file and its exists
        //String path = "C:/temp"; //directory, there will be no output
     
        // creating file object from given path
        File file = new File(path);
     
        // check for if file exits and than this File object actually
           represent a file
        // because exists() method returns true even if path points to
           a directory
        if(file.exists() &amp;&amp; !file.isDirectory()){
            System.out.println("File exits in File System
                       - Java check successful");
        }
     
        // isFile() from File class can check if its file
        // and it exists together     
        if(file.isFile()){
            System.out.println("Provided path is a file and it exists");
        }
         
    }
 
}
Output:
File exits in File System - Java check successful
Provided path is a file and it exists

That's all on How to check if a File or directory exists or not from Java program. You can use this code to check if a file exists or not before starting to write into it or open for any operation. Just keep in mind that the File.exists() method returns true if the given path is either file or directory so make sure that you also check for that condition as shown in this example.

A better way is to use the isFile() method which returns true if this instance is represented by a file and it exists.

Thursday, April 23, 2020

How to Create File and Directory in Java with Example

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

Many beginners confused with the fact that same class java.io.File is used to create both file and directory in Java. I agree, this is not very intuitive and  junior developers probably start looking for a class called java.io.Directory, which doesn't exists. On the other hand, creating file and directory are simple in Java, as java.io.File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These method returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully. There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command.

For checking, whether a file or directory exists or not, we will use java.io.File.exists() method, this method returns true, if file or directory is already there. To see complete behaviour in action, please run this program twice with same inputs. First time it will create directory and file, and second time, it will just say that they already exists.

Java Program to make File and Directory


This is the complete code of our sample Java program to create file and directory in Java. As I told same object java.io.File is used to represent both file and directory,  its important to name variable properly to distinguish between them e.g. using prefix "f" for file and "dir" for directory, or something similar.

After that we are checking if directory already exists or not by using exists() method from java.io.File class, extremely useful to prevent accidental overwrite of old data. If directory doesn't already exists then we call mkdir() method from File class to actually create a directory, thankfully name is similar to popular command mkdir, which is used to create directory in both Windows and Linux operating systems. This method returns a boolean value, which can be used to check if creation of directory is successful or not, you can either leverage this value for error handling or printing error message.

Once directory is ready, we are creating a File object by passing string path. This file object is further used to check if any file of same name already exists on same location or not. If not then only we create file, using createNewFile() of java.io.File class.

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

Similar to mkdir() method, this also returns a boolean to pass result of operation. It will return true if file is successfully created otherwise false, which may be due to various reasons e.g. not having sufficient permissions to create file, or there is not enough space to accommodate new files etc.

Code Sample

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
* Simple Java program to create File and Directory in Java, without using
* any third-party library.
* @author http://oraclejavacertified.blogspot.com/
*
*/
public class FileDemo {

    public static void main(String args[]) throws IOException {

        Scanner reader = new Scanner(System.in);
        boolean success = false;

        System.out.println("Enter path of directory to create");
        String dir = reader.nextLine();

        // Creating new directory in Java, if it doesn't exists
        File directory = new File(dir);
        if (directory.exists()) {
            System.out.println("Directory already exists ...");

        } else {
            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();
            if (success) {
                System.out.printf("Successfully created new directory : %s%n", dir);
            } else {
                System.out.printf("Failed to create new directory: %s%n", dir);
            }
        }

        // Creating new file in Java, only if not exists
        System.out.println("Enter file name to be created ");
        String filename = reader.nextLine();

        File f = new File(filename);
        if (f.exists()) {
            System.out.println("File already exists");

        } else {
            System.out.println("No such file exists, creating now");
            success = f.createNewFile();
            if (success) {
                System.out.printf("Successfully created new file: %s%n", f);
            } else {
                System.out.printf("Failed to create new file: %s%n", f);
            }
        }

        // close Scanner to prevent resource leak
        reader.close();

    }
}

Output :

First run :
Enter path of directory to create
C:\dhoom3
Directory not exists, creating now
Successfully created new directory : C:\dhoom3
Enter file name to be created
Abhishek.txt
No such file exists, creating now
Successfully created new file: Abhishek.txt

Second run :
Enter path of directory to create
C:\dhoom3
Directory already exists ...
Enter file name to be created
Abhishek.txt
File already exists

Don't forget to close Scanner once done, a good practice to prevent resource leak in Java. Alternatively you can also use try-with-resource statements from Java 7, which facilitate automatic resource clean up for you. That not only take care of releasing resources once you are done with that, but also removes coding headache and finally block from above code, making it more concise and readable. That's all about how to create or make file and directory in Java.

Wednesday, April 22, 2020

2 Ways to Read a Text File in Java - Examples

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

You can read a text file in Java 6 by using BufferedReader or Scanner class. Both classes provide convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes and Readers like FileReader are used to read character data. BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so it's more efficient if you are reading large files. BufferedReader is also there from JDK 1 itself while Scanner was added to Java 5.

Scanner has more features than BufferedReader, when it comes to file reading, for example you can specify any delimiter instead of new line, which is not possible with BufferedReader. Java 7 added new File API, which makes it reading/writing from file even more easier.

It's also possible to read entire file in one line in Java 7, but given most of the projects are still running on Java 6, its good to know about these two ways to read a text file in Java. For Java beginners, I also suggest to refer a good book like Cay S. Horstmann, Core Java Volume 1 and 2 to learn basics of Java programming.

How to read a text file in Java?


You an read a text file in Java program by using BufferedReader and Scanner and we will discuss steps to read a file in this article. First we will see how to use Scanner class to read a file line by line in Java and then we will learn how to use BufferedReader class to do the same.

Solution 1 - Reading File using Scanner


Scanner class is defined in java.util package, so first step is to import this class in your Java program. Once you imported this class, you can create object of Scanner by passing a FileInputStream to it, pointing to the file you want to read. Now you are all set to read a text file line by line in Java. Scanner provides a method called hasNextLine() which returns true if file has one more line to read.

This check is platform independent so it will work in both Windows and UNIX even though line separator is different in these two operating system e.g. line separator is \n in Windows and \r\n in UNIX. You can read data from file by calling nextLine() method, this will return the next line and advance the file pointer to next line. This method return a String object representing a line in file. You can use a while() loop as shown in our first example, to read all lines from file one by one.

You can also see Core Java Volume 2 - Advanced Features by Cay S. Horstmann to learn more about how to use Scanner to read a file in Java.

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

Solution 2 - Reading File using BufferedReader


BufferedReader provides another way to read file line by line in Java. It follows decorator pattern and adds buffering capability to an existing reader. You can create an object of InputStreamReader by passing FileInputStream, pointing to the text file you want to read. Optionally, you can also provide character encoding to the InputStreamReader, if you don't then it will use platform's default character encoding. InputStreamReader actually acts as a bridge between streams and reader classes.

Once you have an object of BufferedReader, you can call readLine() method to read the next line from file. This method return a String object containing data from file, if there is no more line to read then this method return null. By using this properly, you can write a while loop to read a file line by line in Java, as shown in our second example.

Though I have not closed buffered reader here, you should do it on your real production code, as suggested earlier on right way to close streams in Java. Its better to call close() method on finally block. If you are on Java 7, consider using try-with-resource statement to automatically close resources once you are done with it.

Oracle Java Tutorial and Materials, Oracle Java Prep, Oracle Java Guides

Java Program to read a file in Java


Here is our complete Java program to read a file in Java. This program contains two examples, first example shows how to read a text file using Scanner class and second example shows how to read a file using BufferedReader class. Both classes are defined in java.util package so you need to import them before using it. If you are coding in Eclipse then don't worry, Eclipse will take care of it. In order to run this program from command line,  create a  Java source file with name FileReaderDemo.java and write this program there. Once you are done with it, you can follow steps given on how to run Helloworld in Java to run this program from command line. If you are using Eclipse IDE, then just select a Java project and copy paste this code there, Eclipse will take care rest of it. To run a program in Eclipse, just right click and select "Run as Java Program".

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * Java program to read File in Java. It demonstrate two ways by simple example,
 * one uses java.util.Scanner class and other by using java.io.BufferedReader
 * class.
 *
 * @author http://oraclejavacertified.blogspot.com
 *
 */

public class FileReaderDemo{

    public static void main(String args[]) throws IOException {

        final String FILE_NAME = "C://temp//GDP.txt";

        // 1st way to read File in Java - Using Scanner
        Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
        while (scnr.hasNextLine()) {
            System.out.println(scnr.nextLine());
        }
        scnr.close();

        // 2nd way to read File in Java - Using BufferedReader
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME)));
        String line = buffReader.readLine();
        while (line != null) {
            System.out.println(line);
            line = buffReader.readLine();
        }
    }
}

Output:

United States   18,390.900
China           15,923.626
India           5,750.467      
Japan           5,021.990      
Germany         3,440.437      
Russia          2,827.978      
Brazil          2,656.858      
United Kingdom  2,562.320      
France          2,416.128    
Mexico          2,040.222

That's all about how to read a text file in Java using BufferedReader and Scanner. Use Scanner if you are running on Java 5 or Java 6, or use BufferedReader is you are running on Java 1.4. You can use Files class to read text files form Java 7 onward. Don't forget to close the Scanner and BufferedReader object once you are done with it. Also provide a character encoding if your file's encoding is different than platform's character encoding.

Monday, April 20, 2020

Java 9 - Overview

Java 9, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep

JAVA 9 (aka jdk 1.9) is a major release of JAVA programming language development. Its initial version was released on 21 Sep 2017. The main goals of Java 9 release are −

◉ To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well.

◉ To improve the overall security of the JDK and Java Implementations.

◉ To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms.

◉ To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily.

New Features


There are 90+ enhancements added to Java 8, the most significant ones are mentioned below −

Module − A new kind of Java programing component introduced as module, which is a named, self-describing collection of code and data.

REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform.

HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and server push features.

Improved JavaDocs − Supports HTML5 output generation. Provides a search box to generated API documentation.

Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive.

Collection Factory Methods − New static factory methods for List, Set, and Map interfaces to create immutable instances of those collections.

Private Interface Methods − Enhanced interfaces with private and private static methods.

Process API Improvements − Improved API to control and manage operating system processes.

Stream API Improvements − Enhanced security and robustness by allowing incoming streams of object-serialization data to be filtered.

Try With Resources improvement − Now final variables can be used as resources in the try-with-resources statement.

Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide more information about the status and intended disposition of an API.

Inner Class Diamond Operator − Allow the diamond operator to be used with anonymous classes if the argument type of the inferred type can be denoted.

Optional Class Improvements − New useful methods are added to java.util.Optional class.

Multiresolution Image API − Supports encapsulation of a set of images with different resolutions into a single multiresolution image.

CompletableFuture API improvements − The asynchronous mechanisms of the CompletableFuture class can perform an action when the process exits with ProcessHandle.onExit method.

Lightweight JSON − A lightweight API introduced to consume and generating documents and data streams via json in java 9.

Reactive Streams API − A new Reactive Streams API in Java SE 9 has been introduced to support reactive programming in java 9.

Sunday, April 19, 2020

How to recursive copy directory in Java with sub-directories and file

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Prep

Hello guys, it's a common requirement in Java to copy a whole directory with sub-directories and files but it's not that straight forward, especially not until Java 7. JDK 7 introduced some new file utility methods as part of Java NIO 2 which we will use in this article to show you how to recursively copy a whole directory with sub-directories and files in Java. I'll also show you how you can use Apache Commons if you are not running on Java 7 or higher versions. Basically, You can copy a file or directory by using the copy(Path, Path, CopyOption...) method. The copy fails if the target file exists unless the REPLACE_EXISTING option is specified.

This method can be used to copy directories but, files inside the directory are not copied, so the new directory is empty even when the original directory contains files. This is the key thing to remember because many developers just call this method and think they are done with it. They don't bother to check if the directory is empty or not.

In order to copy the whole directory with all its sub-directories and files, you need to recursively copy each item unless you reach the top of the directory. When copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option.

The following Java code shows how to use the copy method:

import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

Later, I will show you a complete example of copying whole directory recursively with all their content but if you want to learn more about Java NIO and Files utility class I suggest you go through a comprehensive Java course like The Complete Java Masterclass on Udemy. It's also one of the most up-to-date courses to learn Java and covers new features from recent Java releases.

The copyDirectory Example From Apache Commons

If you are thinking that above method is too complex to use this method then you can also try using the copyDirectory(File srcDir, File destDir) method from the Apache Commons IO library instead.

You can use this method from Apache Commons when you are copying a whole directory to a new location and preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however, it is not guaranteed that those operations will succeed.

If the modification operation fails, no indication is provided.

Parameters:
srcDir - an existing directory to copy, must not be null
destDir - the new directory, must not be null

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Learning, Oracle Java Prep

Java Program to Copy a Director with Files and subdirectories


Here is the complete Java program to recursive copy directory in Java with sub-directories and files in Java:

import java.io.File;

import java.io.IOException;

import java.nio.file.FileAlreadyExistsException;

import java.nio.file.FileVisitResult;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.SimpleFileVisitor;

import java.nio.file.attribute.*;

import static java.nio.file.FileVisitResult.*;

import org.apache.commons.io.FileUtils;

/**

   * Java Program to recursive copy directory with sub-directories and files.

   *

   * @author Javin Paul

   */

public class Testing {

    public static void main(String args[]) {

        //copyDir("source", "target");

        copyDirectory("source", "destination");


    }


    /**

     * Java Method to recursive copy directory in Java, including all files and

     * sub-directories. This method, doesn't copy the root directory. For

     * example, it will copy all contents of source directory, but not the

     * source directory itself. which means instead of target directory

     * containing target/source/... it will contain target/...

     *

     * @param source

     * @param destination

     */

    public static void copyDir(String source, String destination) {

        try {

            File srcDir = new File(source);

            File destDir = new File(destination);

            FileUtils.copyDirectory(srcDir, destDir);

            System.out.printf("Method 1 : Directory %s copied 
 successfully to location %s %n", srcDir.getAbsolutePath(), destDir.getAbsolutePath());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static void copyDirectory(String source, String destination) {

        try {

            Files.walkFileTree(Paths.get("source"), 
           new RecursiveFileVisitor(source, destination));

            System.out.printf("Method 2 : Directory %s copied 
            successfully to location %s %n", source, destination);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    private static class RecursiveFileVisitor extends SimpleFileVisitor {

        private final Path source;

        private final Path target;

        private RecursiveFileVisitor(String source, String target) {

            this.source = Paths.get(source);

            this.target = Paths.get(target);

        }

        @Override

        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {

            Path newdir = target.resolve(source.relativize(dir));

            try {

                Files.copy(dir, newdir);

            } catch (FileAlreadyExistsException x) {

                // ignore

            } catch (IOException x) {

                System.out.format("Failed to create: %s: %s%n", newdir, x);

                return SKIP_SUBTREE;

            }

            return CONTINUE;

        }

        @Override

        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {

            try {

                Files.copy(file, target.resolve(source.relativize(file)));

            } catch (IOException x) {

                System.out.format("Failed to copy: %s: %s%n", source, x);

            }

            return CONTINUE;

        }

        @Override

        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {

            if (exc == null) {

                Path newdir = target.resolve(source.relativize(dir));

                try {

                    FileTime time = Files.getLastModifiedTime(dir);

                    Files.setLastModifiedTime(newdir, time);

                } catch (IOException x) {

                    System.out.format("Failed to copy all attributes to: %s: %s%n",
                               newdir, x);

                }

            }

            return CONTINUE;

        }

        @Override

        public FileVisitResult visitFileFailed(Path file, IOException exc) {

            System.err.format("Failed to copy: %s: %s%n", file, exc);

            return CONTINUE;

        }

    }

}

Output

Method 1 : Directory D:\Eclipse_workspace\Test\source copied successfully 
to location D:\Eclipse_workspace\Test\target

Method 2 : Directory source copied successfully to location destination

Failed to copy: source: java.nio.file.FileAlreadyExistsException: 
destination\config.properties

Failed to copy: source: java.nio.file.FileAlreadyExistsException: 
destination\java\code\Hello.java

Failed to copy: source: java.nio.file.FileAlreadyExistsException: 
destination\test\HelloTest.java

That's all about how to copy recursively copy a directory in Java with sub-directories and files. If you are on Java 7, use Files.copy() the method, its simple and easy and you don't need to include any third party library, but if you are running on Java 6, then you can either use Apache commons IO library and FileUtils.copy() method or you can write your own routing using FileChannel to copy file from one folder to another in Java.