Posts

Showing posts with the label Java File Tutorial

How to get the last modified date and time of a file or directory in Java

Sometimes before processing a file, you want to check it's last modified date to avoid processing an old file. Though some programmers prefer to attach date in the file name itself, I don't find it a cleaner approach. For example, suppose you are downloading closing prices of stocks and processing at the start of the day and loading into the database. In order to accidently process an old file, you can check the last modified date before processing and if it's in the acceptable range, you can process the file. You can get the last modified date of a file in Java by using java.io.File class. This is a class which represents both file and directory in Java. It contains a method called lastModified() which returns the last modified date of the file. This method returns a long millisecond epoch value, which you can convert to more readable dd MM yyyy HH:mm:sss format by using the SimpleDateFormat class of JDK. In this article, I'll tell you how to get the last modified...

How to read a text file using Scanner in Java? Example Tutorial

As I told you before that there are multiple ways to read a file in Java e.g. FileReader , BufferedReader , and FileInputStream . You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java. Similar to readLine() , Scanner class also have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. you can not only read text but parse it into correct data type e.g. nextInt() can read integer and nextFloat() can read float and so on. Re...

10 Examples to read a text file in Java

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReader , BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. You can also use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file. Read more �