Java provides a built-in class java.io.File for standard file operations. This can be used for renaming files as well. The following example shows how a file can be renamed in Java.
import java.io.File;
/**
* How to rename a file in Java 7 and below.
* @author jj
*/
public class RenameFile1 {
public static void main(String[] args) {
// Please ensure that the following file/folder exists
File f = new File("c:/temp/test1.txt");
// The following file should not exist while running the program
File rF = new File("c:/temp/test2.txt");
if(f.renameTo(rF)) {
System.out.println("File was successfully renamed");
} else {
System.out.println("Error: Unable to rename file");
}
}
}
Since Java 8, a new class java.nio.file.Files was introduced. This is a more reliable and flexible option than the java.io.File. The following example shows the recommended way of renaming files in Java 8.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* How to rename a file in Java 8 and above.
* @author jj
*/
public class RenameFile2 {
public static void main(String[] args) {
Path f = Paths.get("c:/temp/test1.txt");
Path rF = Paths.get("c:/temp/test2.txt");
try {
Files.move(f, rF, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File was successfully renamed");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error: Unable to rename file");
}
}
}
Posted in Java | Comments Off on How to Rename a File in Java
Perfect square numbers are natural numbers which can be expressed in the form n = a * a. Hence any number which is the result of multiplying a number with itself is known as a perfect square number. For example, 9 is a perfect square number since 9 = 3 * 3.
Finding Perfect Square Numbers in a Range Using Java
The following Java program finds all perfect square numbers between two given numbers. The following program prints perfect numbers between 1 and 100. We iterate through the range of values and then check whether each number is a perfect number or not.
To check whether a number is perfect square, we take the square root of the number and then convert it to an integer and then multiply the integer with itself. Then we check whether it is same as the given number.
// Finding perfect square numbers in a range using Java
import java.io.IOException;
public class SquareNumbersInRange {
public static void main(String[] args) throws IOException {
int starting_number = 1;
int ending_number = 100;
System.out.println("Perfect Numbers between "+starting_number+ " and "+ending_number);
for (int i = starting_number; i <= ending_number; i++) {
int number = i;
int sqrt = (int) Math.sqrt(number);
if (sqrt * sqrt == number) {
System.out.println(number+ " = "+sqrt+"*"+sqrt);
}
}
}
}
Posted in Java | Comments Off on Finding Perfect Square Numbers in a Range Using Java
A key concept in cryptography is the concept of hash values. A hash is a unique value corresponding to a given data with the following properties,
- It is impossible to arrive at the original message from hash.
- Two different messages practically cannot have the same hash.
- Modifying message changes the corresponding hash.
- It is easy to generate the hash value with the above properties.
There are a number of well known algorithms for generating hash values. Two of the most popular ones are SHA and MD5. The following example Java program creates an MD5 hash for a given string. This program uses the java.security.MessageDigest class for creating the MD5 hash. MessageDigest is also capable of generating hash values using SHA-1 and SHA-256 algorithms.
Note that we are using DataTypeConverter to convert the arbitrary hash binary value in readable hexadecimal format. This enables us to share the hash over email or printed material. This conversion is not required if you don't want a readable version of MD5 hash.
import java.security.MessageDigest;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
/**
* Demonstrates how to generate MD5 hash using Java
* @author JJ
*/
public class MD5HashGenerator {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Please enter data for which MD5 is required:");
String data = sn.nextLine();
MD5HashGenerator sj = new MD5HashGenerator();
String hash = sj.getMD5Hash(data);
System.out.println("The MD5 (hexadecimal encoded) hash is:"+hash);
}
/**
* Returns a hexadecimal encoded MD5 hash for the input String.
* @param data
* @return
*/
private String getMD5Hash(String data) {
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(data.getBytes("UTF-8"));
return bytesToHex(hash); // make it printable
}catch(Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
* to a hexadecimal string. Note that this generates hexadecimal in upper case.
* @param hash
* @return
*/
private String bytesToHex(byte[] hash) {
return DatatypeConverter.printHexBinary(hash);
}
}
Posted in Java | Comments Off on How to Generate MD5 Hash in Java
Nowadays any non trivial application written in Java would need to access cloud services over HTTP. Whether you are accessing a cloud web service or trying to download a webpage programmatically, the approach is same. Java provides a dedicated class HttpURLConnection for getting data over the HTTP protocol. The following sample Java program demonstrates the use of HttpURLConnection to download a web page. The following Java program would print the contents of Google's home page (http://www.google.com) on the command line console.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Java program to download a web page over http protocol.
* Requires active Internet connection.
*/
public class DownloadPage {
public static void main(String[] args) {
String pageToDownload = "http://www.google.com";
String downloadedContent = downloadPage(pageToDownload);
System.out.println(downloadedContent);
}
/**
* Download a webpage using HttpURLConnection class.
* @param pageToDownload
* @return
*/
private static String downloadPage(String pageToDownload) {
String result = "";
try {
URL url = new URL(pageToDownload);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // we are getting the contents
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
reader.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
The same approach can be used to access a cloud web service returning XML or JSON data. The following sample Java program demonstrates the use of HttpURLConnection to return 7 day weather forecast of London City using the OpenWeatherMap API. The data returned is in JSON format,
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Uses OpenWeatherMap API and HttpURLConnection to download 7 day weather
* forecast of London city in JSON format.
*/
public class WeatherDownload {
public static void main(String[] args) {
// Please see http://openweathermap.org/forecast16
String weatherAPIUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=7&appid=bd82977b86bf27fb59a04b61b657fb6f";
String downloadedContent = downloadWeather(weatherAPIUrl);
System.out.println("7 day weather forecast of London city");
System.out.println(downloadedContent);
}
/**
* Access a cloud API using HttpURLConnection class.
* @param weatherAPIUrl
* @return
*/
private static String downloadWeather(String weatherAPIUrl) {
String result = "";
try {
URL url = new URL(weatherAPIUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // we are getting the contents
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
reader.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Posted in Java | Comments Off on How to Download a File in Java
In cryptography, SHA (Secure Hash Algorithm) is a hash function which generates a unique value for a given data. This unique value (known as hash) has the following properties,
- It is impossible to arrive at the original message from hash.
- Two different messages practically cannot have the same hash.
- Modifying message changes the corresponding hash.
- It is easy to generate the hash value with the above properties.
These one way hash values are the fundamental building blocks of modern cryptography. One of the popular algorithms for hash generation is SHA. There are a number of variants of SHA algorithms such as SHA-1 and SHA-256. Out of these SHA-1 was the most popular until security vulnerabilities were found in them. Nowadays the recommended hash function for digital security (digital signatures, security certificates etc.) is SHA-256.
The following program shows how to generate SHA256 hash in Java. This program uses the built-in class java.security.MessageDigest for creating the SHA256 hash. Note that the hash output generated is binary data and hence if you try to convert it directly to String, you will get unprintable weird looking characters. Hence usually the bytes are converted to a readable hexadecimal form so that hash values can be printed or send over email. I have used javax.xml.bind.DatatypeConverter built-in class to convert byte array to a hexadecimal string.
import java.security.MessageDigest;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
/**
* Demonstrates how to generate SHA256 hash in Java
* @author JJ
*/
public class SHA256InJava {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Please enter data for which SHA256 is required:");
String data = sn.nextLine();
SHA256InJava sj = new SHA256InJava();
String hash = sj.getSHA256Hash(data);
System.out.println("The SHA256 (hexadecimal encoded) hash is:"+hash);
}
/**
* Returns a hexadecimal encoded SHA-256 hash for the input String.
* @param data
* @return
*/
private String getSHA256Hash(String data) {
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes("UTF-8"));
return bytesToHex(hash); // make it printable
}catch(Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
* to a hexadecimal string. Note that this generates hexadecimal in upper case.
* @param hash
* @return
*/
private String bytesToHex(byte[] hash) {
return DatatypeConverter.printHexBinary(hash);
}
}
Posted in Java | Comments Off on How To Generate SHA256 Hash in Java