HTML

How to write to File in Java using BufferedWriter

You can use either OutputStream or Writer class in Java to write data to a file in Java. For example, you can use a combination of FileWriter and BufferedWriter to write text content into a text file in Java. If you want to write raw bytes consider using FileOutputStream class. Just remember that InputStream is used to read data and OutputStream is used to write data to file or socket. You can write anything to file e.g. String, integer, float values etc. Java provides DataOutputStream to write different data type directly into file e.g. writeInt() to write integer values, writeFloat() to write floating point values into file and writeUTF() to write String into File.  BufferedWriter, like its counterpart BufferedReader, allows you to perform buffered IO, which can drastically improve performance while reading large files.

java.lang.NoClassDefFoundError: org/dom4j/DocumentException [Solution]

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException comes when your program is using DOM4j library but necessary JAR is not present. This error can also come when you are indirectly using DOM4j library e.g. when you use Apache POI library to read XLSX file in Java,  this library needs dom4j.jar in your classpath. Not just this one but there are several other libraries which use this JAR internally, if you are using any of them but don't have this JAR then your program will compile fine but fail at runtime because JVM will try to load this class but will not be able to find it on the classpath. Some curious developers might ask, why it didn't fail during compile time if JAR was not present there? Well, the reason for that is that your code might not be using any class file directly from the dom4j.jar file.

2 Ways to Read a Text File in Java - Examples

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.

How to format numbers in Java? - NumberFormat Example

You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them. Mostly numbers which are used to represent monetary value e.g. price, amount etc requires a comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollars then you would like to see it as 1,000,000 rather than 1000000. Clearly the first one is more readable the second one. Of course, you can further format to add currency based upon locale, but this tutorial is not about that. In this tutorial, we are just looking to format numbers and group them. Its second part of my number formatting article, in the first part you have learned how to format floating point numbers in Java and in this article shows step by step example to group numbers and add commas between them.

How to get first and last elements form ArrayList in Java

There are times when you need to get the first or last element of an ArrayList. One of the common scenarios where you need first and last element of a list is supposed you have a sorted list and wants to get the highest and lowest element? How do you get that? The first element is your lowest and the last element is your highest, provided ArrayList is sorted in ascending order. If its opposite then the first element would be the maximum and last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and the last element is on index, size - 1. If you know how to get the size of ArrayList then you can easily get those two values. Just remember, that you need to use size() method and not length, which is used to get the length of array. Earlier we have seen how to get first and last element from linked list and In this tutorial, we are going to see an example of how to get the last element from ArrayList in Java.

How to reverse words in String Java? [Solution]

In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding questions, so you will also learn how to take a requirement, how to fill gaps in the requirement by asking the right question. A String is nothing but a sentence, which may contain multiple works, or just contain a single word or it may be empty. Your program must produce a String contains the word in reverse order, for example, if given input is "Java is Great" then your program should return "Great is Java".  Now, if you are a good programmer then you should have some right questions for the programmer.

How to convert ByteBuffer to String in Java

You can easily convert ByteBuffer to String  in Java if you know how to convert byte array to String. Why? because it's very easy to convert ByteBuffer to a byte array and vice versa. All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array. Though always remember to provide correct character encoding while converting byte array to String. For example, if you know that ByteBuffer is filled with bytes encoded in UTF-8 then you must use the same encoding while creating String from that byte array. String class provides an overloaded constructor which accepts character encoding along with byte array.  You can use the snippet shared in this example to do the job. ByteBuffer is one of the very useful class in java.nio package which is used to read data from channels and write data into channel directly.

java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [Solved]

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject error means that your Java program needed a class called org.apache.xmlbeans.XmlObject but JVM is not able to find that in your application's CLASSPATH. You can see the actual cause of this error is "java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject". The most probable reason for this error could be a missing JAR file. In order to solve this error, you need to first find out which JAR file this class belongs. If you look at the error message it's clearly saying that it's from xmlbeans package, it means this class belongs to XMLBeans library.

What is fail safe and fail fast Iterator in Java?

Java Collections supports two types of Iterator, fail safe and fail fast. The main distinction between a fail-fast and fail-safe Iterator is whether or not the underlying collection can be modified while its begin iterated. If you have used Collection like ArrayList then you know that when you iterate over them, no other thread should modify the collection. If Iterator detects any structural change after iteration has begun e.g adding or removing a new element then it throws ConcurrentModificationException,  this is known as fail-fast behavior and these iterators are called fail-fast iterator because they fail as soon as they detect any modification . Though it's not necessary that iterator will throw this exception when multiple threads modified it simultaneously. it can happen even with the single thread when you try to remove elements  by using ArrayList's remove() method instead of Iterator's remove method, as discussed in my earlier post, 2 ways to remove objects from ArrayList.

How to convert String to double in Java with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating point value into the Double object. Rest of the methods e.g. valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?

Though both synchronized ArrayList and CopyOnWriteArrayList provides you thread-safety and you can use both of them when your list is shared between multiple threads, there is a subtle difference between them, Synchronized ArrayList is a synchronized collection while CopyOnWriteArrayList is a concurrent collection. What does this mean? It means is that CopyOnWriteArrayList is designed keeping concurrency in mind and it is more scalable than synchronized ArrayList if the list is primarily used for reading. You know that ArrayList is not synchronized, so you cannot directly use it in a multi-threaded environment where you list is accessed and modified by multiple threads. In order to use ArrayList in such environment, you need to first get a synchronized list by calling Collections.synchronizedList().