How To Copy Files From One Directory to Another in Java: Example

Hello folks. I have been programming in Java for a long time, and you won't believe it, but there was no file copy method in the Java API until Java 7. Our options were either to: write it ourselves using a FileInputStream, a FileOutputStream, and a buffer to copy bytes from one to the other; or, better yet, use the FileChannel.transferTo() method or the Apache Commons FileUtils, which was a lifesaver in those days and still is today. 

JDK has evolved now, and you have a decent API to copy files from one directory to another. In this article, I'll show you both the pre-Java code for copying files from one directory to another as well post Java 7 code, which makes this task a lot easier.

Multithreading in Java

Every programmer comes across Multithreading and for some reason, it has been considered hard to understand. Well, it's not. In this blog, we will go through some basics of multithreading and in the process will try to understand why it is such an important topic in software development.

A program can have multiple processes and Multithreading allows us to run these multiple processing units concurrently. Our programs by default run on a Single thread also known as the main thread. Multithreading is useful because:

SKP’s Algorithms and Data Structures #9: Java Problem: Monkeys in the Garden

[Question/Problem Statement is the Property of Techgig] 

Monkeys in the Garden [www.techgig.com]

In a garden, trees are arranged in a circular fashion with an equal distance between two adjacent trees. The height of trees may vary. Two monkeys live in that garden and they were very close to each other. One day they quarreled due to some misunderstanding. None of them were ready to leave the garden. But each one of them wants that if the other wants to meet him, it should take maximum possible time to reach him, given that they both live in the same garden.

SKP’s Algorithms and Data Structures #8: Java Problem: Simple Inheritance (OOPs)

[Question/Problem Statement is the Property of Techgig]
 
Java Inheritance / Simple OOPs [www.techgig.com]
Create Two Classes:

BaseClass
The Rectangle class should have two data fields-width and height of int types. The class should have display() method, to print the width and height of the rectangle separated by space.

DerivedClass
The RectangleArea class is Derived from Rectangle class, i.e., it is the Sub-Class of Rectangle class. The class should have read_input() method, to Read the Values of width and height of the Rectangle. The RectangleArea class should also Overload the display() Method to Print the Area (width*height) of the Rectangle.

Input Format
The First and Only Line of Input contains two space-separated Integers denoting the width and height of the Rectangle.

Constraints
1 <= width,height <= 10^3

Output Format
The Output Should Consist of Exactly Two Lines.
In the First Line, Print the Width and Height of the Rectangle Separated by Space.
In the Second Line, Print the Area of the Rectangle.


[Explanation of the Solution]
This is the Simplest of all OOPs Questions! Demonstration of Inheritance and Overriding (Very Loosely, Liskov Substitution of SOLID).


[Source Code, Sumith Puri (c) 2021 — Free to Use and Distribute]
Java
 




x
67


1
 /*    
2
  * Techgig Core Java Basics Problem - Get Simple OOPs Right!  
3
  * Author: Sumith Puri [I Bleed Java!]; GitHub: @sumithpuri;  
4
  */   
5
     
6
  import java.io.*;   
7
  import java.util.*;   
8
   
9
   
10
  class Rectangle {  
11
   
12
    private int width;  
13
    private int height;  
14
   
15
    public void display() {  
16
   
17
      System.out.println(width + " " + height);  
18
    }  
19
   
20
    public int getWidth() {  
21
   
22
      return width;  
23
    }  
24
   
25
    public void setWidth(int width) {  
26
   
27
      this.width=width;  
28
    }  
29
   
30
    public int getHeight() {  
31
   
32
      return height;  
33
    }  
34
   
35
    public void setHeight(int height) {  
36
   
37
      this.height=height;  
38
    }  
39
  }  
40
   
41
  class RectangleArea extends Rectangle {  
42
   
43
    public void read_input() {  
44
   
45
     Scanner scanner = new Scanner (System.in);   
46
       
47
     setWidth(scanner.nextInt());   
48
     setHeight(scanner.nextInt());  
49
    }  
50
   
51
    public void display() {  
52
   
53
      super.display();  
54
      System.out.println(getWidth()*getHeight());  
55
    }  
56
  }  
57
     
58
  public class CandidateCode {   
59
     
60
   public static void main(String args[] ) throws Exception {   
61
     
62
     RectangleArea rectangleArea = new RectangleArea();  
63
     rectangleArea.read_input();  
64
   
65
     rectangleArea.display();  
66
   }   
67
 } 



SKP’s Algorithms and Data Structures #7: Functional Programming and Java Lambdas

[Question/Problem Statement is the Property of Techgig]

Java Advanced — Lambda Expressions [www.techgig.com] 
Write the Following Methods that Return a Lambda Expression Performing a Specified Action: Perform Operation isOdd(): The Lambda Expression must return if a Number is Odd or  If it is Even. Perform Operation isPrime(): The lambda expression must return if a number is prime or if it is composite. PerformOperation isPalindrome(): The Lambda Expression must return if a number is a Palindrome or if it is not.

Input Format
Input is as Show in the Format Below
Input
3
1 3
2 7
3 7777

Constraints
NA

Output Format
Output is as Show in the Format Below
Output
ODD
PRIME
PALINDROME


[Explanation of the Solution]
This is a Good Question to Refresh Java 8 Lambdas. In my Solution, I Implemented the Functional Interfaces within my main() Method and assigned it to Local Reference Variables.


SKP’s Algorithms and Data Structures #6: Java Problem: Active Traders

[Question/Problem Statement is the Property of HackerRank]

Algorithms/Data Structures — [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Active. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."


Example
n = 23
"customers = {"Bigcorp", "Bigcorp", "Acme", "Bigcorp", "Zork", "Zork", "Abe", "Bigcorp", "Acme", "Bigcorp", "Bigcorp", "Zork", "Bigcorp", "Zork", "Zork", "Bigcorp", "Acme", "Bigcorp", "Acme", "Bigcorp", "Acme", "Littlecorp", "Nadircorp"}."

"Bigcorp had 10 Trades out of 23, which is 43.48% of the Total Trades."
"Both Acme and Zork had 5 trades, which is 21.74% of the Total Trades."
"The Littlecorp, Nadircorp, and Abe had 1 Trade Each, which is 4.35%..."

"So the Answer is ["Acme","Bigcorp","Zork"] (In Alphabetical Order) Because only These Three Companies Placed at least 5% of the Trades.


Function Description

Complete the Function mostActive in the Editor Below.

mostActive
has the following parameter:
String customers[n]: An Array Customer Names
(Actual Question Says String Array, But Signature is List of Strings)

SKP’s Algorithms and Data Structures #5: Java Problem: Changes in Usernames

[Question/Problem Statement is the Adapted from HackerRank]

Algorithms/Data Structures — [Problem Solving] 
There is a Specific Need for Changes in a List of Usernames. In a given List of Usernames — For Each Username — If the Username can be Modified and Moved Ahead in a Dictionary. The Allowed Modification is that Alphabets can change Positions in the Given Username.

Example
usernames[] = {"Aba", "Cat"}
 
"Aba" can be Changed to only "Baa" — Hence, It can Never Find a Place Ahead in the Dictionary. Hence, Output will be "NO". "Cat" can be Changed to "Act", "Atc", "Tca", "Tac", "Cta" and Definitely "Act" will Find a Place Before "Cat" in the Dictionary. Hence, Output will be "YES".

[Function Description]
Complete the function possibleChanges in the Editor Below.
 
possibleChanges has the Following Parameters:
String usernames[n]: An Array of User Names
 
Returns String[n]: An Array with "YES" or "NO" Based on Feasibility
(Actual Question Says String Array, But Signature is List of Strings)


Constraints
• [No Special Constraints Exist, But Cannot Recall Exactly]


Input Format 
"The First Line Contains an Integer, n, the Number of Elements in Usernames.",
"Each Line of the n Subsequent Lines (where 0 < i < n) contains a String usernames[i]."        

[Sample Case 0 — Sample Input For Custom Testing]         
5
Aba
Cat
Boby
Buba
Bapg
Sungi
Lapg
Acba
       
Sample Output (Each Should Be on a Separate Line) 
NO YES NO YES YES YES YES YES
   

 
[Explanation of the Solution]
This is again a Good Question from Hacker Rank to Test Your Logic / Problem Solving Abilities. The Core Point to Handle is that For Each Combination of 2 Alphabets that Exists in the Username String > We Need to Check if the Latter Occurring Character (ASCII) is Less than the Former Occurring Character (ASCII). For Example in the String "Bapg" — For a Selection of "Ba" from "Bapg" — We have "a" Occurring Before "B" in the English Alphabet. We can Have Two Loops (One Nested) to Decide for a Combination of Each Two Alphabets. The Time Complexity of this Solution is O(n^2).
 


[Source Code, Sumith Puri (c) 2021 — Free to Use and Distribute]

SKP’s Java/Java EE Gotchas: Clustered Nodes Issue Using Apache Lucene 5.4.y

So, We just spent about 28+ days — using Stack Overflow and Hibernate Search Forums as also various other resources to 'FIX' the strangest of issues using Hibernate Search and Apache Lucene. The right help or pointer came from the 'Hibernate Search Committers/Creators' (Official Forums). Thanks a lot to 'sanne.grinovero'.

Issue Description: In a (non-replicated) clustered environment, if the Indexing by Lucene or Hibernate Search is done from the Same Database (Instance) using the Same Data the Results obtained are Different on Different Nodes. In other words, the Same Data from the Same Database Instance Indexed using the Same Code Yields a Different Result Set for the Same Search Term (Index Contents are Different on Different Machines).


Issue Resolution / Root Cause: The point to note is that, if you open a 'Hibernate Session' that you use for your 'Apache Lucene or Hibernate Search Indexing' and if a 'Runtime/Exception' occurs before you 'Close' the session, the results that are obtained across different machines, when queried using the same search term. Though this occurred after the 'console logs' reported that the Index is '100% Successfully Completed' — It has led to an inconsistent index across machine. My analysis is that 'session.close()' below may be leading to some 'flushing or committing to the indexing', which leads to the inconsistency when a runtime exception occurs — even after indexing is reported complete by the Hibernate/Hibernate Search on the 'Console Logs'.

Suggestion: Make sure that there are no Runtime Exceptions (or Errors) before Closing the Session. Even if you find that the Indexing is 100% Complete and there is an Exception right at the End — Please do not Ignore/Keep/Park it (Considering it a Minor or Unrelated Error) for a fix at the 'End of Dev Cycle' as it may Impact Results. This is true for any seemingly unrelated exception that may occur before calling 'session.close()'.

I am pasting the statement here from Hibernate Search Forums (Committer), which may be useful for all of you and helped us to finally resolve this error:  If a batch of documents failed, you might have a block of documents missing in one of the indexes (and this could happen several times). By default errors are logged, you might want to hook up an ErrorHandler to raise a more serious notification to your admins — if logs are ignored.



The culprit line of code, pointed out in red. [CULPRIT LINE OF CODE - WHERE RUNTIME EXCEPTION OCCURS - POINTED OUT USING ARROW]

SKP’s Java/Java EE Gotchas: Clash of the Titans, C++ vs. Java!

As a Software Engineer, the mind is trained to seek optimizations in every aspect of development and ooze out every bit of available CPU Resource to deliver a performing application. This begins not only in designing the algorithm or coming out with efficient and robust architecture but right onto the choice of programming language. Most of us, as we spend years in our jobs — tend to be proficient in at least one of these.  
 
Recently, I spent some time checking on the Performance (not a very detailed study) of the various programming languages. One, by researching on the Internet; Two, by developing small programs and benchmarking. The legacy languages — be it ASM or C still rule in terms of performance. But these are definitely ruled out for enterprise applications due to the complexity in development, maintainability, need for object orientation, and interoperability. They still will win for mission-critical or real-time systems, which need performance over these parameters. There were languages I briefly read about, including other performance comparisons on the internet. These include Python, PHP, Perl, and Ruby. Considering all aspects and needs of current enterprise development, it is C++ and Java which outscore the other in terms of speed. According to other comparisons [Google for 'Performance of Programming Languages'] spread over the net, they clearly outshine others in all speed benchmarks. So much for my blog title :-) So when these titans are pit against each other in real-time, considering all aspects of memory and execution time — Java is floored. Though I have spent the last ~17 years (In 2021) of my life coding and perfecting my Java and J2EE skill — I suddenly feel... Ahem, Slow! One of the problem statements to verify this is given below (along with the associated code) and the associated execution parameters. 
 


[Disclaimer: Problem Statement given below is the property of www.codechef.com

In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3, and n/4. But these numbers are all rounded down (the banks have to make a profit). You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? Input The input will contain several test cases (not more than 10). Each test case is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin. 
 
JAVA SOLUTION (Will Be Uploaded Later)
C++ SOLUTION (Will Be Uploaded Later)
 
RESULTS

TIME

Spring, Hibernate, EhCache Recipe

A Simple Scenario explaining the Usage and Performance, when using EhCache (2nd Level Cache of along with Hibernate in a Spring environment. The performance results are taken using mySQL as the Database. 

Though this Example is from Spring 2.5.x and Hibernate 3.x and EhCache 1.4, MySQL 5.0 => The Concepts Demonstrated will Continue to Hold Good for any Version of any Make of Second Level Cache Product with Hibernate (Optionally, Spring) such as Infinispan, Redis, Hazelcast, ...

[Download Sample Code] Please be informed that the size is about 10MB; as i have provided all the dependencies.

In this example, I need to retrieve close to 5,000 records in a single fetch and then cache this information. As usual, setup Spring contexts in your Spring configuration file. I have just one class, which is a Hibernate DAO, HibernateDoctorDAO.java. The dependency injection hierarchy is dataSource sessionFactory hibernateTemplate. hibernateTemplate is then injected into the HibernateDoctorDAO.java at runtime by the Spring Framework.

The Implementations of Each of These Are:
dataSource > org.apache.commons.dbcp.BasicDataSource
sessionFactory > org.springframework.orm.hibernate3.LocalSessionFactoryBean
hibernateTemplate > org.springframework.orm.hibernate3.HibernateTemplate

The results clearly shows the difference in performance with EhCache enabled, even in this simple example:
 
PERFORMANCE COMPARISON (In Seconds)
==============================
QUERY FETCH TIME (INITIAL): 0.599
QUERY FETCH TIME (HIBERNATE CACHE): 0.212
QUERY FETCH TIME (2ND LEVEL CACHE): 0.091
Version Reference > Spring-2.5, Hibernate-3.0, EhCache-1.4, mySQL-5.0
 

Instructions: Unzip the file and start by creating the database. Any mySQL database that is compatible with the MySQL Connector 5.0.8 is fine for this example. You will have to create the database data_explosion (USERNAME: root, PASSWORD: architect.2012) and the table DOCTOR_TABLE. You can use the provided doctor.sql as reference. Then run the java standalone com.sumsoft.spring.orm.hibernate.dataload.JDBCDataLoader to create and load a large number of arbitary records into the DOCTOR_TABLE. You can ignore or remove every invocation that is to PATIENT_TABLE, as this is only additional for this example. Then use spring_hibernate_cache.bat to run the application. Though not tested on UNIX, you may write a script similar to the batch file to run this application. 

SKP’s Java/Java EE Gotchas: Revisiting Java SE 9 Features, Part 1

Preparing for an interview? Want to just revisit Java SE 9 features? Trying to recollect or revise Java SE programming constructs? Let me take you back in time to what was introduced first in Java SE 9? Join me for this tutorial series on Java as we all eagerly await the official release of Java SE 14!

As I promised, I am back with the code samples of my earlier article Java SE 9... What's New? You may refer the earlier article to understand the newly introduced features at a high level. This article provides the code samples for each of the features.

You may download the code samples for the following new features here. (Import as eclipse project, set compiler/environment as Java 9. Run the main class 'Java9Application' to see the output/outcome of the Code Samples.)

I plan to start by re-visiting a Java 8 feature, Default Interface Methods.

5 Different Ways to Create Objects in Java

Being Java developers, we usually create lots of objects daily, but we always use dependency management systems e.g. Spring to create these objects. However, there are more ways to create objects, which we will study in this article.

There are five total ways to create objects in Java, which are explained below with their examples followed by bytecode of the line which is creating the object.

5 Courses to Learn Java Concurrency in Depth in 2019

If you are a Java developer and looking for some awesome resources, e.g. books and courses, to improve your multithreading and concurrency skills in Java, then you have come to the right place! In the past, I have shared books and tutorials on Java concurrency and multithreading, and in this article, I am going to talk about some of the best free and paid courses to learn multithreading and concurrency.

You can join these courses to improve your understanding of Java concurrency and multithreading. It's one of the most important skills for Java developers, as almost all the companies who interview Java developers pay particular attention to his knowledge and experience in this area.