Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some breathing space but it was still not as simple as it should be, like in Python or Ruby. By using Java 7 new File API and Java 8's new features like lambda expression and stream API, Java is now close to Python or other utility languages, when it comes to reading the file into String.
Difference between Direct, Non Direct and Mapped ByteBuffer in Java
ByteBuffer is one of the important class of Java NIO API. It was introduced in java.nio package on JDK 1.4, it not only allows you to operate on on heap byte arrays but also with direct memory, which resides outside the JVM. There are mainly three types f ByteBuffer, Direct, Non Direct and mapped byte buffers. You can create both direct and non direct buffers using java.nio.ByteBuffer class, while MappedByteBuffer is a subclass of ByteBuffer, which is created by FileChannel.map() method, to operate on memory mapped file. Main difference between direct and non direct byte buffers are there memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory, while direct byte buffer are outside of JVM and memory is not allocated from heap. You can remember this fact by there name, Direct indicates working with memory directly. Due to this reason, direct byte buffers are also not affected by Garbage Collection. MappedByteBuffer is also a type of direct byte buffer, which represent memory mapped region of a file. In this Java NIO tutorial, you will see couple of more differences between direct, non direct and mapped byte buffers, which will help you to understand the concept and there usage better. If you love books like me and wants to learn advanced concept e.g. high performance and low latency application development, performance tuning and JVM internals, I suggest to take a look at Definitive guide of Java Performance, one of the must read book for Java programmers.
Labels:
java IO tutorial
How to delete a directory with files in Java - Example
Deleting an empty directory is easy in Java, just use delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and sub directories inside this folder. This may seem cumbersome, but unfortunately there is no method which can delete directory with files in Java, not even on Java 7 Files and Paths class. So there is two choices, either you write your own method to recursively delete all files and folder before deleting a directory or alternatively you can use an open source utility library like Apache Commons IO which will do this for you. BTW, If you have to do this without using any third party library than you can use the example shown in this tutorial. You know what, I have asked this question couple of times to Java developers and only 3 out of 10 knows that you cannot delete directory with files in Java. I am not surprised because this is the kind of detail which is not obvious. Until you do it, you don't know this. Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder, as shown in first example of this tutorial. Java 7 got much better with files and directory support but there also unfortunately no direct method to delete a directory with files. Though, In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.
Labels:
core java
,
java IO tutorial
,
programming
How to Read File in One Line in JDK 7 or Java 8
Reading a file in Java is not simple, it requires lots of boiler plate code, as we have seen in our earlier example of reading text files. Various things had to wrapped e.g. a FileInputStream inside a BufferedReader, loops with weird terminating conditions had to be specified and so forth. From JDK 7 onward, you can do a lot better. It provides lots of useful classes e.g. Files and Paths to deal with file and their actual path. In this article, we will see how we can read a file in just one line. Of course, your production code won't be like that, especially if you are reading a few gigabytes into memory and want to pay attention to the character set, if you don't specify, by platform's default character encoding will be used. In short, you will need a little more code, but for quick and dirty file reading this should do the trick. By the way, It wouldn't be a one-liner if it had exception handling. In a production application you would need to deal with the fact that the file isn't there e.g. displaying an error for the user, posting metrics, logging the error etc, but it certainly be lot less boiler code than it used to be.
Labels:
Java 8
,
java IO tutorial
How to Read/Write from RandomAccessFile in Java
Random access file is a special kind of file in Java which allows non-sequential or random access to any location in file. This means you don't need to start from 1st line if you want to read line number 10, you can directly go to line 10 and read. It's similar to array data structure, Just like you can access any element in array by index you can read any content from file by using file pointer. A random access file actually behaves like a large array of bytes stored in file system and that's why its very useful for low latency applications which needs some kind of persistence e.g. in front office trading application and FIX Engine, you can use random access file to store FIX sequence numbers or all open orders. This will be handy when you recover from crash and you need to build your in memory cache to the state just before the crash. RandomAccessFile provides you ability to read and write into any random access file. When you read content from file, you start with current location of file pointer and pointer is moved forward past how many bytes are read. Similarly when you write data into random access file, it starts writing from current location of file pointer and then advances the file pointer past number of files written. Random access is achieved by setting file pointer to any arbitrary location using seek() method. You can also get current location by calling getFilePointer() method. There are two main ways to read and write data into RandomAccessFile, either you can use Channel e.g. SeekableByteChannel and ByteBuffer class from Java NIO, this allows you to read data from file to byte buffer or write data from byte buffer to random access file. Alternatively you can also use various read() and write() method from RandomAccessFile e.g readBoolean(), readInt(), readLine() or readUTF(). This is a two part Java IO tutorial, in this part we will learn how to read and write String from RandomAccess file in Java without using Java NIO channels and in next part we will learn how to read bytes using ByteBuffer and Channel API. .
Labels:
core java
,
java IO tutorial
Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java
File API is very important one in Java, it gives access of File system to Java programs. Though Java's file API is rich, there are lot of subtleties to know when you use them. One of the common query programmer's has about file path is difference between getPath(), getCanonicalPath() and getAbsolutePath() methods, why there are three methods to get file path and what happens if you call getPath() in place of getCanonicalPath(). By the way, before understanding difference between getPath(), getAbsolutePath() and getCanonicalPath() let's understand the concept behind this methods, i.e. difference between path, absolute path, and canonical path. In general, a path is way to get to a particular file or directory in a file system, it can be absolute (also known as full path) or relative e.g. relative to current location. Absolute path defines path from root of the file system e.g. C:\\ or D:\\ in Windows and from / in UNIX based operating systems e.g. Linux or Solaris. Canonical path is little bit tricky, because all canonical path is absolute, but vice-versa is not true. It actually defines a unique absolute path to the file from root of the file system. For example, C://temp/names.txt is a canonical path to names.txt in Windows, and /home/javinpaul/test/names.txt is canonical path in Linux. On the other hand, there can be many absolute path to the same file, including the canonical path which has just seen. For example another absolute path to the same file in Windows can be C://temp/./names.txt; similarly in UNIX /home/javinpaul/test/./names.txt is another absolute path to the same file. So you can say that, absolute path may contain meta characters like . and .. to represent current and parent directory. In rest of this article, we will learn difference between getPath(), getAbsolutePath() and getCanonical() Path by looking at values it return for a particular file.
Labels:
core java
,
interview questions
,
java IO tutorial
,
programming
2 Examples to read Zip Files in Java, ZipFile vs ZipInputStream
ZIP format is one of the most popular compression mechanism in computer world. A Zip file may contains multiples files or folder in compressed format. Java API provides extensive support to read Zip files, all classes related to zip file processing are located in java.util.zip package. One of the most common task related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder. In this tutorial we will learn how to do this task in Java. There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has header field containing size of items in number of bytes. Which means you can iterate all entries without actually decompressing the zip file. ZipFile class accepts a java.io.File or String file name, it opens a ZIP file for reading and UTF-8 charset is used to decode the entry names and comments. Main benefit of using ZipFile over ZipInputStream is that it uses random access to iterate over different entries, while ZipInputStream is sequential, because it works with stream, due to which it's not able to move positions freely. It has to read and decompress all zip data in order to reach EOF for each entry and read header of next entry. That's why its better to use ZipFile class over ZipInputStream for iterating over all entries from archive. We will learn more about how to use read Zip file in Java, by following an example. By the way, code should work with zip file created by any zip utility e.g. WinZip, WinRAR or any other tool, .ZIP format permits multiple compression algorithms.. I have tested with Winzip in Windows 8, but it should work with zip file created by any tool.
Labels:
coding
,
core java
,
java IO tutorial
,
programming
Subscribe to:
Posts
(
Atom
)