Java File IO – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 09:12:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java File IO – Java2Blog https://java2blog.com 32 32 Count Files in Directory in Java https://java2blog.com/count-files-in-directory-java/?utm_source=rss&utm_medium=rss&utm_campaign=count-files-in-directory-java https://java2blog.com/count-files-in-directory-java/#respond Tue, 14 Feb 2023 08:02:07 +0000 https://java2blog.com/?p=22457 Using java.io.File Class

Before moving forwards, it is important to know the available items in the current directory. You may also create the same structure to follow along with this article. Our current directory (E:\Test) has the following structure:

  • E:\Test – It has seven items, four text files and three folders (FolderA, FolderB, FolderC, File1.txt, File2.txt, File3.txt, and File4.txt).
  • E:\Test\FolderA – It contains four text files ( File1.txt, File2.txt, File3.txt, and File4.txt).
  • E:\Test\FolderB – It has two text files (File1.txt and File2.txt).
  • E:\Test\FolderC – Only one text file lives here (File1.txt).

Use File.listFiles() Method

We can use File.listFiles() method in the following four scenarios:

  1. To count files in the current directory, excluding sub-directories.
  2. To count files in the current directory, including sub-directories.
  3. To count files and folders in the current directory, excluding sub-directories.
  4. To count files and folders in the current directory, including sub-directories.

Note that the code will be similar to one another for all the above situations except for small changes. So, we will thoroughly learn the first code example and later only discuss the part different from the previous one. So, let’s start with the first example code below.

Count Files in the Current Directory (Excluding Sub-directories)

To count files in the current directory, excluding sub-directories:

  • Instantiate the File class by specifying the directory.
  • Call a function we defined to count the files only in the current parent directory.
  • Inside the function, we invoked in the previous step, use a for loop to iterate over all items in the specified directory.
  • Use the if statement to check whether it is a file. If it is, increment the counter by 1; otherwise, move to the next iteration.
import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInCurrentDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInCurrentDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          if (file.isFile()) {
              count++;
          }
      }
      return count;
   }
}
Number of Files:4

In the main method of the CountFilesInDirectory class, we created an object of the File class (instantiated the File class) by specifying an E:\Test directory and saved its reference in directory variable.

Next, we called the countFilesInCurrentDirectory() method and passed the File object named directory we created in the previous step. On successful execution of this method, it returned a file counter that we saved in the fileCount variable. So, let’s see how this method counts the files.

The countFilesInCurrentDirectory() is a static method defined in the CountFilesInDirectory class to count files in the provided directory. We declared and initialized a count variable used to maintain a file counter inside this function.

Next, we used a for loop with the listFiles() method to iterate over every item in the specified directory. We used the if statement with the isFile() function for each iteration to check whether the current item is a file. We incremented the count variable by 1 if the if condition is fulfilled; otherwise, we moved to the next iteration.

Once the loop was over, we returned the count variable, whose value will be saved in the fileCount variable, which will be used to print a message on the console using the System.out.println() method.

Now, the point is what the listFiles() and isFile() methods are doing here. The listFiles() is one of the methods of the File class, which returns an array of abstract pathnames representing the directories and files in the specified directory denoted by this abstract pathname which satisfies the given filter (if any).

Remember, we will only get an array of files if the given path is a directory; otherwise, it will generate a java.lang.NullPointerException exception and return null.

The listFiles() method is an overloaded method, which means we can use it in the following three ways where the first method does not take any parameter, the second accepts the FilenameFilter object, and the third takes FileFilter object as their parameters (we used the first method in our code above).

public File[] listFiles()
public File[] listFiles(FilenameFilter filter)
public File[] listFiles(FileFilter filter)

Moving to the next method, which is isFile(). It is also a method of the File class, used to check whether the file represented by an abstract pathname is the normal file. This function returns a Boolean value, True if the current item is a file; otherwise, False.

Count Files in the Current Directory (Including Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          if (file.isFile()) {
              count++;
          }

          if (file.isDirectory()) {
              count += countFilesInDirectory(file);
          }
      }
      return count;
    }
}
Number of Files:11

This code example is the same, but we added another if statement inside the for loop in the countFilesInDirectory() method (line 19 to line 21). This if statement used the isDirectory() method to check whether the current item is a directory.

Like the isFile() method, it also returned a Boolean value, True if the condition is satisfied; otherwise, False. If the condition is fulfilled, the countFilesInDirectory() method calls a copy of itself, getting the current item (a directory) as a parameter.

NOTE: We used recursion here because countFilesInDirectory() method is calling a copy of itself.

Count Files & Folders in Current Directory (Excluding Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          count++;
      }
      return count;
  }
}
Number of Files:7

Inside the for loop in the countFilesInDirectory() method, we removed both if statements to count files and folders from the current parent directory. Note that we are still incrementing the count variable by 1 in each iteration. For example, we got 7 because E:\Test contains four text files and three folders (FolderA, FolderB, FolderC, File1.txt, File2.txt, File3.txt, and File4.txt).

Count Files & Folders in Current Directory (Including Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          count++
          if (file.isDirectory()) {
              count += countFilesInDirectory(file);
          }
      }
      return count;
  }
}
Number of Files:14

This code is similar to the immediate previous example. But, we have an if statement in the for loop (line 16 to line 18), which assesses if the current item is a directory or not using the isDirectory() method.

If it is, we also used recursion to count files in that directory. You can compare the above output by looking at the directory structure given at the beginning of this article.

If you are not concerned about sub-directories and only want to count files and folders in the current parent directory, then we can use the most straightforward solution using the File.list() method.

Use File.list() Method

To count files and folders in the current parent directory, excluding sub-directories:

  • Create an object of the File class by passing a directory as an argument.
  • Use the .list() method to get a String-type array containing filenames (files and folders).
  • Use the .length property of the String type array (received from the previous step) to get a count of the array elements.
import java.io.File;

public class CountFilesInDirectory {
    public static void main(String[] args) {
        File directory = new File("E:\\Test");
        String[] fileArray = directory.list();
        int fileCount = fileArray.length;
        System.out.println("Number of Files:" + fileCount);
    }
}
Number of Files:7

The above code fence is similar to the previous code examples except for one difference; we used the .list() method here. After instantiating the File class, we used the .list() method to get an array of strings with filenames (files and directories) in the directory represented by this abstract pathname.

We saved this array in the fileArray variable; after that, we accessed the .length property of the fileArray array to know the count of elements in it, which we used to print a message on the console using println() method.

We can also replace line 7 with File[] fileArray = directory.listFiles(); and get the same results. Now, the question is, how does the File.list() method differ from File.listFiles()? Both methods essentially do the same but:

  • File.list() method returns a String array containing filenames (directories and files).
  • File.listFiles() returns an array of the File class of the same.

Now, where to choose which method? We must choose between these two methods wherever we are concerned about speed and memory consumption. Usually, a String array (returned by File.list()) would be faster and consume less memory as compared to the File array (returned by File.listFiles()). To dive into more details, you can check this page.

Using java.nio.file.DirectoryStream Class

The StreamAPI approach is useful when we:

  • Do not want to use the Java.io.File class.
  • Look for a solution using fewer resources while working with large directories.
  • More responsive while working with remote directories.

In this article, we are using the DirectorySteam class to do the following:

  1. To count files in the current directory, excluding sub-directories.
  2. To count files in the current directory, including sub-directories.
  3. To count files and folders in the current directory, excluding sub-directories.
  4. To count files and folders in the current directory, including sub-directories.

Again, the code sample will be similar to one another for all the above scenarios so that we will learn each step for the first example code, later, will explain the newly added piece of code only.

Count Files in the Current Directory (Excluding Sub-directories)

To count files in the current directory, excluding sub-directories:

  • Create an ArrayList of Strings.
  • Create a directory stream to access the contents of the given directory.
  • Use the for loop to iterate over the directory steam created in the previous step.
  • For every iteration of the for loop, use the if to check if the current item is not a directory. If not, use the .add method to add the current string item to ArrayList.
  • Use the .size() method to get the size of the ArrayList.
  • Use the try-catch method to handle exceptions.
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {    
                if(!Files.isDirectory(path))
                    fileNames.add(path.toString());
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }
        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:4

Inside the main method of the CountFilesInDirectory class, we created a new ArrayList of Strings called fileNames. The ArrayList is a class in Java that implements the List interface and provides an array-like data structure for storing elements. The diamond operator is a shorthand notation specifying the type of elements the ArrayList will hold. In this case, it is a list of Strings.

Inside the try block, we created a new DirectoryStream called directoryStream that was used to access the directory’s contents. Note that the DirectoryStream is of type Path. The Files.newDirectoryStream method created a new directory stream bound to the specified directory. Here, the Paths.get("E:\\Test") was used to obtain a Path object representing the file system directory E:\Test.

Next, we used a for loop to iterate over each element in the directoryStream object and assigned it to the variable path of type Path. For each iteration, we checked if the path is not a directory by calling the Files.isDirectory(path) method in the if statement; if it is not a directory, it will add the path to the fileNames list. Finally, the path.toString() method was used to get the string representation of the path.

The for loop was used to iterate over the contents of the directory and only added the file names to the fileNames list, not the directory names.

Here, if the try block generates the IOException (a type of exception thrown when an input/output operation fails), the catch block will be executed. The exception.printStackTrace() method was called inside the catch block, which printed the stack trace of the exception to the console. The stack trace shows the sequence of method calls that led to the exception, which can be helpful for debugging.

Finally, we used the .size() method to get the size of the fileNames list and print it on the console.

Count Files in the Current Directory (Including Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                if(Files.isDirectory(path)){
                    DirectoryStream<Path> subDirectoryStream = Files
                          .newDirectoryStream(Paths.get(path.toString()));
                    for (Path p: subDirectoryStream)
                        fileNames.add(p.toString());
                }
                else{
                    fileNames.add(path.toString());
                }
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:11

This code is similar to the immediate previous example, but we replaced the following

if(!Files.isDirectory(path))
  fileNames.add(path.toString());

with

if(Files.isDirectory(path)){
    DirectoryStream<Path> subDirectoryStream = Files
        .newDirectoryStream(Paths.get(path.toString()));
    for (Path p: subDirectoryStream)
         fileNames.add(p.toString());
}
else{
    fileNames.add(path.toString());
}

inside the for loop. We did so to check if the current path is a directory or not using the Files.isDirectory(path) method. If it is a directory, we created a new subDirectoryStream using Files.newDirectoryStream(Paths.get(path.toString())), which was used to access the contents/items of the sub-directory represented by the current path.

Next, we iterated over each element in the subDirectoryStream object and assigned it to the variable p of type Path and added the path to the fileNames list using the .add() method. On the other hand, in the else part, we directly added the path to fileNames.

Note that this code was used to recursively iterate over the contents of the directory/subdirectories and add the file names to the fileNames list, not the directory names.

Count Files & Folders in the Current Directory (Excluding Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:7

For this code, we removed all the conditionals from the for loop located in the main method to count files and folders from the current parent directory.

Count Files & Folders in the Current Directory (Including Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                fileNames.add(path.toString());
                if(Files.isDirectory(path)){
                    DirectoryStream<Path> subDirectoryStream = Files
                          .newDirectoryStream(Paths.get(path.toString()));
                    for (Path p: subDirectoryStream)
                        fileNames.add(p.toString());
                }
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:14

This code is similar to the code where we were counting files in the current directory, including sub-directories; here, we eliminated the else block to count files and folders from the current directory/sub-directories.’

That’s all about how to count files in Directory in Java.

]]>
https://java2blog.com/count-files-in-directory-java/feed/ 0
How to Remove Extension from Filename in Java https://java2blog.com/remove-extension-from-filename-java/?utm_source=rss&utm_medium=rss&utm_campaign=remove-extension-from-filename-java https://java2blog.com/remove-extension-from-filename-java/#respond Fri, 16 Sep 2022 12:38:16 +0000 https://java2blog.com/?p=20543 In this post, we will see how to remove extension from filename in java.

Ways to Remove extension from filename in java

There are multiple ways to remove extension from filename in java. Let’s go through them.

Using substring() and lastIndexOf() methods

You can first find last index of dot(.) using String’s lastIndexOf() method and then use substring() to extract the part of String upto the last index of dot(.).

Here is an example:

package org.arpit.java2blog;

public class RemoveExtensionFromFile {

    public static void main(String[] args) {
        String fileName = "C:\\txtFiles\\temp.txt";
        String fileNameWithoutExtension = removeExtension(fileName);
        System.out.println("Complete file path without extension => "+fileNameWithoutExtension);
    }
    public static String removeExtension(final String s)
    {
        return s != null && s.lastIndexOf(".") > 0 ? s.substring(0, s.lastIndexOf(".")) : s;
    }

}

Output:

Complete file path without extension => C:\txtFiles\temp

You can also get extension of file in java using above method.

Using replaceAll() method

You can also use String’s replaceAll() method to remove extension of filename in Java. We will use regex to identify characters after last dot(.) and replace it with empty string.
Here \\.\\w+

  • \\. is used to find . in the String
  • \\w+ is used to find any character after dot(.)
package org.arpit.java2blog;

public class RemoveExtensionFromFileReplaceAll {
    public static void main(String[] args) {
        String fileName = "C:\\txtFiles\\temp.txt";
        String fileNameWithoutExtension = fileName.replaceAll("\\.\\w+","");
        System.out.println("Complete file path without extension => "+fileNameWithoutExtension);
    }
}

Output:

Complete file path without extension => C:\txtFiles\temp

Using Apache common library

You can use FilenameUtils‘s getBaseName() method to get filename without extension. If you are looking for complete path, you can use removeExtension() method.
Add the following dependency to pom.xml.

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
 </dependency>

Here is an example:

package org.arpit.java2blog;

import org.apache.commons.io.FilenameUtils;

public class RemoveExtensionFromFileNameApache {

    public static void main(String[] args) {
        String fileName = "C:\\txtFiles\\temp.txt";
        String fileNameWithoutExtension = FilenameUtils.getBaseName(fileName);
        System.out.println("File name without extension => "+fileNameWithoutExtension);
        String fileNamePathWithoutExtension =  FilenameUtils.removeExtension(fileName);
        System.out.println("Complete file path without extension => "+fileNamePathWithoutExtension);
    }
}

Output:

File name without extension => temp
Complete file path without extension => C:\txtFiles\temp

That’s all about remove extension from filename in java.

]]>
https://java2blog.com/remove-extension-from-filename-java/feed/ 0
How to Get Temp Directory Path in Java https://java2blog.com/get-temp-directory-path-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-temp-directory-path-java https://java2blog.com/get-temp-directory-path-java/#respond Thu, 15 Sep 2022 17:31:22 +0000 https://java2blog.com/?p=20491 In this post, we will see how to get temp directory path in java.

Get Temp Directory Path in Java

Using System.getProperty()

To get the temp directory path, you can simply use System.getProperty("java.io.tmpdir"). It will return default temporary folder based on your operating system.

Default temp directory path
Windows : %USER%\AppData\Local\Temp
Linux/Unix: /tmp

Let’s see with the help of example:

package org.arpit.java2blog;

public class GetTemporaryPathMain {

    public static void main(String[] args) {
        String tempDirPath = System.getProperty("java.io.tmpdir");
        System.out.println("Temp directory path : " + tempDirPath);
    }
}

Output:

Temp directory path : C:\Users\Arpit\AppData\Local\Temp\

By Creating Temp File and Extracting Temp Path

We can also create temp file and extract temp directory path using String’s substring() method.

Using java.io.File

To get temp directory path:

  • Use File.createTempFile() to create temp file.
  • Get absolute path using File's getAbsolutePath() method.
  • Use substring() method to extract temp directory path from absolute path.
package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;

public class CreateFileAndGetTempDirMain {

    public static void main(String[] args) {
        try {
            // Create temp file
            File temp = File.createTempFile("temp_", ".tmp");

            String absTempFilePath = temp.getAbsolutePath();
            System.out.println("Temp file path : " + absTempFilePath);

            // Get temp directory path using substring method
            String tempDirPath = absTempFilePath
                    .substring(0, absTempFilePath.lastIndexOf(File.separator));

            System.out.println("Temp directory path : " + tempDirPath);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Temp file path : C:\Users\Arpit\AppData\Local\Temp\temp_10478314566038976912.tmp
Temp directory path : C:\Users\Arpit\AppData\Local\Temp

Using java.nio.File.Files

To get temp directory path:

  • Use Files.createTempFile() to create temp file.
  • Get absolute path using toString() method.
  • Use substring() method to extract temp directory path from absolute path.
package org.arpit.java2blog;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateFileNIOAndGetTempDirMain {

    public static void main(String[] args) {
        try {
            // Create temp file
            Path temp = Files.createTempFile("temp_", ".tmp");

            String absTempFilePath = temp.toString();
            System.out.println("Temp file path : " + absTempFilePath);

            String fileSeparator = FileSystems.getDefault().getSeparator();
            String tempDirPath = absTempFilePath
                    .substring(0, absTempFilePath.lastIndexOf(fileSeparator));

            System.out.println("Temp directory path : " + tempDirPath);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Temp file path : C:\Users\Arpit\AppData\Local\Temp\temp_6905627814634776014.tmp
Temp directory path : C:\Users\Arpit\AppData\Local\Temp

Override Default Temp Directory Path

If you want to override temp directory path, you can run java program with JVM arguments as -Djava.io.tmpdir=Temo_file_path

For example:
If you want set temp directory path as C:\temp, you can run java program with JVM argument as -Djava.io.tmpdir=C:\temp

That’s all about how to get temp directory path in Java.

]]>
https://java2blog.com/get-temp-directory-path-java/feed/ 0
Convert Outputstream to Byte Array in Java https://java2blog.com/convert-outputstream-to-byte-array-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-outputstream-to-byte-array-java https://java2blog.com/convert-outputstream-to-byte-array-java/#respond Wed, 16 Feb 2022 12:50:23 +0000 https://java2blog.com/?p=19377 In this post, we will see how to convert OutputStream to Byte array in Java.

Convert OutputStream to Byte array in Java

Here are steps to convert OutputStream to Byte array in java.

  • Create instance of ByteArrayOutputStream baos
  • Write data to ByteArrayOutputStream baos
  • Extract byte[] using toByteArray() method.
package org.arpit.java2blog;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OutputStreamToByteArray {

    public static void main(String[] args) throws IOException {

        String str="Java2blog";

        // Creates OutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Get bytes from String
        byte[] array = str.getBytes();

        // Write data to OutputStream
        baos.write(array);

        // Convert OutputStream to byte array
        byte bytes[] = baos.toByteArray();

        System.out.println("Print output:");

        for(int x = 0; x < bytes.length; x++) {
            // Print original characters
            System.out.print((char)bytes[x]  + "");
        }
        System.out.println("   ");
    }
}

Output:

Print output:
Java2blog

Convert OutputStream to ByteBuffer in Java

To convert OutputStream to ByteBuffer in Java, we need to add one more step to above method.

  • Create instance of ByteArrayOutputStream baos
  • Write data to ByteArrayOutputStream baos
  • Extract byte[] using toByteArray() method.
  • Convert byte array to ByteBuffer using ByteBuffer.wrap(byte[]) method.
package org.arpit.java2blog;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class OutputStreamToByteBuffer {

    public static void main(String[] args) throws IOException {

        String str="Java2blog";

        // Creates OutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Get bytes from String
        byte[] array = str.getBytes();

        // Write data to OutputStream
        baos.write(array);

        // Get bytes[] from ByteArrayOutputStream
        byte bytes[] = baos.toByteArray();

        // Convert bytep[] to ByteBuffer
        ByteBuffer bb= ByteBuffer.wrap(bytes);

        System.out.println(bb);
    }
}

Output:

java.nio.HeapByteBuffer[pos=0 lim=9 cap=9]

That’s all about how to convert Outputstream to Byte Array in Java.

]]>
https://java2blog.com/convert-outputstream-to-byte-array-java/feed/ 0
How to get current working directory in java https://java2blog.com/how-to-get-current-working-directory-in/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-get-current-working-directory-in https://java2blog.com/how-to-get-current-working-directory-in/#respond Sat, 26 Dec 2020 18:45:00 +0000 http://www.java2blog.com/?p=277
In this post, we will see how to get current working directory in java.
There are four ways to do it.

Using property user.dir

We can use System.getProperty(“user.dir”) to get current working directory path.
package org.arpit.java2blog;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

    public static void main(String[] args)
    {
        System.out.println("--------------");
        String currentWorkingDirectory;
        currentWorkingDirectory = System.getProperty("user.dir");
        System.out.println("Current working directory is : "+currentWorkingDirectory);
        System.out.println("--------------");
    }
}
When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir

Using getAbsolutePath()

We can use file.getAbos
package org.arpit.java2blog;

import java.io.File;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

    public static void main(String[] args)
    {
        System.out.println("--------------");
        String currentWorkingDirectory="";
        // . denotes current working directory
        File file=new File(".");
        currentWorkingDirectory=file.getAbsolutePath();
        System.out.println("Current working directory is : "+currentWorkingDirectory);
        System.out.println("--------------");
    }
}
When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/.

Using Paths.get() (Java 7+)

You can use Paths.get("") method get current working directory in java.

package org.arpit.java2blog;

import java.nio.file.Path;
import java.nio.file.Paths;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

    public static void main(String[] args)
    {
        String currentWorkingDirectory;
        System.out.println("--------------");
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        currentWorkingDirectory=s.toString();
        System.out.println("Current working directory is : "+currentWorkingDirectory);
        System.out.println("--------------");
    }
}

When I ran above program, I got below output:

Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/

Using FileSystems.getDefault() (Java 7+)

You can use FileSystem.getDefault() method get current working directory in java.

package org.arpit.java2blog;

import java.nio.file.FileSystems;
import java.nio.file.Path;

/*
 * @Author Arpit Mandliya
 */
public class getCurretWorkingDirectoryMain {

    public static void main(String[] args)
    {
        String currentWorkingDirectory;
        System.out.println("--------------");
        Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
        currentWorkingDirectory=path.toString();
        System.out.println("Current working directory is : "+currentWorkingDirectory);
        System.out.println("--------------");
    }
}

When I ran above program, I got below output:

Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/

That’s all about how to get current working directory in java.

]]>
https://java2blog.com/how-to-get-current-working-directory-in/feed/ 0
Difference between Scanner and BufferReader in java https://java2blog.com/difference-between-scanner-bufferreader-java/?utm_source=rss&utm_medium=rss&utm_campaign=difference-between-scanner-bufferreader-java https://java2blog.com/difference-between-scanner-bufferreader-java/#respond Sat, 08 Aug 2020 06:35:52 +0000 https://java2blog.com/?p=10187 In this post, we will see difference between Scanner and BufferReader in java.

Java has two classes that have been used for reading files for a very long time.
These two classes are Scanner and BufferedReader.
In this post, we are going to find major differences and similarities between the two classes.

Introduction

Let’s first go through quick introduction to Scanner and BufferReader classes.

Scanner

Scanner class can be used for user input by importing from java.util package.
A user can read numbers from System.in(From your command line) by using Scanner class.

Scanner sc  = new Scanner(System.in);
int i = sc.nextInt();

Let’s try a simple example to understand the working of the Scanner class.

package com.mycompany.hellonetbeans;

import java.util.Scanner;

/**
 *
 * @author arti
 */
public class UseOfScanner {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String name = scan.next();
        int num = scan.nextInt();
        scan.close();

        System.out.println("my name is: " + name);
        System.out.println("my lucky number is: " + num);

    }
}

The output of the above program will be:

FooBar 9
my name is: FooBar
my lucky number is: 9

If you don’t want to read from terminal only and want to read from a given file in that case, Scanner class can be used.

Scanner sc = new Scanner(new File("fileName"));
while (sc.hasNextLine()){
     System.out.println(sc.nextLine());
}

BufferedReader

BufferedReader class can be used by importing from java.io package. It reads characters from any input stream line. If you want to read from a file by using BufferedReader, you need to use an appropriate file reader. It can use readLine() to read data line by line.

BufferedReader br = new BufferedReader(new FileReader(“fileName”));

BufferedReader buffers characters and uses it in efficient readings of characters, arrays, lines, etc.

Let’s understand the functioning of BufferedReader by an example

package com.mycompany.hellonetbeans;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author arti
 */
public class BufferedReaderExample {

    public static void main(String[] args) throws IOException {

        String line;
        try {
            BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(UseOfScanner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Output of the above code will be

Hi, this is an example.
line 1
line 2
line 3

Difference between Scanner and BufferedReader

  1. If you have a small application where you don’t care much about synchronization and concurrency, you can use the Scanner class whereas in a thread-safe environment BufferedReader will be a good choice.
  2. Scanner class has a smaller buffer memory of 1024 chars, whereas BufferedReader has a default buffer memory of 8192 chars, and that too can be extended.
  3. Scanner class comes from JDK 1.5, so old applications that support JDK 1.5 can not use Scanner class. BufferedReader class is with java from JDK 1.1, so it supports applications that use older versions of java.
  4. Scanner class uses regular expression in parsing the strings, by default, white space gets set as a delimiter, but you can set any other delimiter.
  5. BufferedReader is only used for reading data, whereas Scanner class is used for reading as well as parsing of data.

That’s all about difference between Scanner and BufferReader in java.

]]>
https://java2blog.com/difference-between-scanner-bufferreader-java/feed/ 0
Read UTF-8 Encoded Data in java https://java2blog.com/read-utf-8-encoded-data-java/?utm_source=rss&utm_medium=rss&utm_campaign=read-utf-8-encoded-data-java https://java2blog.com/read-utf-8-encoded-data-java/#respond Sun, 29 Mar 2020 06:58:16 +0000 https://java2blog.com/?p=9132 In this post, we will see how to read UTF-8 Encoded Data.

Sometimes, we have to deal with UTF-8 Encoded Data in our application. It may be due localization or may be processing data from user input.

There are multiple ways to read UTF-8 Encoded Data in Java.

Using Files’s newBufferedReader()

We can use java.nio.file.Files's newBufferedReader() to read UTF8 data to String.

package org.arpit.java2blog;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadUTF8NewBufferReaderMain {

    public static void main(String[] args) {
        readUTF8UsingnewBufferReader();
    }

    // using newBufferedReader method of java.nio.file.Files
    public static void readUTF8UsingnewBufferReader() {
        Path path = FileSystems.getDefault().getPath("/users/apple/WriteUTF8newBufferWriter.txt");
        Charset charset = Charset.forName("UTF-8");
        try {
            BufferedReader read = Files.newBufferedReader(path, charset);
            String line = null;
            while ((line = read.readLine()) != null) {
                System.out.println(line);
            }
            read.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

यह फ़ाइल UTF-8 newBufferWriter से लिखी गई है

Please note that WriteUTF8newBufferWriter.txt was written from this example.

Using BufferedReader

We need to pass encoding as UTF8 while creating new InputStreamReader.

package org.arpit.java2blog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class ReadUTF8DataMain {
    public static void main(String[] args) {
        try {
            File utf8FilePath = new File("/users/apple/UTFDemo.txt");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(utf8FilePath), "UTF8"));

            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

Output:

UTF-8 Demo for java2blog.com
यह हिंदी का वाक्य है

Please note that UTFDemo.txt was written from this example.

Using DataInputStream’s readUTF() method

We can use DataInputStream readUTF() to read UTF8 data to file.

package org.arpit.java2blog;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadUTFDataMain {

    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("/users/apple/WriteUTFDemo.txt");
            DataInputStream dis = new DataInputStream(fis);
            String utf8FileData = dis.readUTF();
            System.out.println(utf8FileData);
            dis.close();
        } catch (EOFException ex) {
            System.out.println(ex.toString());
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}
आप कैसे हैं

Please note that WriteUTFDemo.txt was written from this example.

That’s all about how to write UTF-8 Encoded Data in java

]]>
https://java2blog.com/read-utf-8-encoded-data-java/feed/ 0
Write UTF-8 Encoded Data in java https://java2blog.com/write-utf-8-encoded-data-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=write-utf-8-encoded-data-in-java https://java2blog.com/write-utf-8-encoded-data-in-java/#respond Sun, 29 Mar 2020 06:54:59 +0000 https://java2blog.com/?p=9119 In this post, we will see how to write UTF-8 Encoded Data.

Sometimes, we have to deal with UTF-8 Encoded Data in our application. It may be due localization or may be processing data from user input.

We will use Hindi language sentences to write in file.

There are three ways to write UTF-8 Encoded Data in Java.

Using Files’s newBufferWriter()

We can use java.nio.file.Files's newBufferedWriter() to write UTF8 data to file.

package org.arpit.java2blog;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteUTF8NewBufferWriter {

    public static void main(String[] args) {
        writeUTF8UsingnewBufferWriter();
    }

    // using newBufferedWriter method of java.nio.file.Files
    private static void writeUTF8UsingnewBufferWriter() {
        Path path = FileSystems.getDefault().getPath("/users/apple/WriteUTF8newBufferWriter.txt");

        Charset charset = Charset.forName("UTF-8");

        try {
            BufferedWriter writer = Files.newBufferedWriter(path, charset);
            writer.write("यह फ़ाइल UTF-8 newBufferWriter से लिखी गई है");
            writer.flush();
            writer.close();
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
}

When you run above program, WriteUTF8newBufferWriter.txt will be created at /users/apple/WriteUTF8newBufferWriter.txt.
Let’s open the file and have a look at content.

WriteUTF-8NewBufferWriter

Using BufferedWriter

We need to pass encoding as UTF8 while creating new OutputStreamWriter.

package org.arpit.java2blog;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class WriteUTF8DataMain {
    public static void main(String[] args) {
        try {
            File utf8FilePath = new File("/users/apple/UTFDemo.txt");

            Writer writer = new BufferedWriter(new OutputStreamWriter(
                            new FileOutputStream(utf8FilePath), "UTF8"));

            writer.append("UTF-8 Demo for java2blog.com").append("\r\n");
            writer.append("यह हिंदी का वाक्य है").append("\r\n");

            writer.flush();
            writer.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

When you run above program, UTFDemo.txt will be created at /users/apple/UTFDemo.txt.
Let’s open the file and have a look at content.

UTFDemo

Using DataOutputStream’s writeUTF() method

We can use DataOutputStream's writeUTF() to write UTF8 data to file.

package org.arpit.java2blog;

import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteUTFMain {

    public static void main(String[] args) {
        try { 
        FileOutputStream fos = new FileOutputStream("/users/apple/WriteUTFDemo.txt");
         DataOutputStream dos = new DataOutputStream(fos);
         dos.writeUTF("आप कैसे हैं");
         dos.close();
        }
        catch(EOFException ex) {
             System.out.println(ex.toString());
          }
          catch(IOException ex) {
             System.out.println(ex.toString());
          }
    }
}

Output:

WeiteUTFDemo

When you run above program, WriteUTFDemo.txt will be created at /users/apple/WriteUTFDemo.txt.
That’s all about how to write UTF-8 Encoded Data in java

]]>
https://java2blog.com/write-utf-8-encoded-data-in-java/feed/ 0
Java read file line by line https://java2blog.com/java-read-file-line-by-line/?utm_source=rss&utm_medium=rss&utm_campaign=java-read-file-line-by-line https://java2blog.com/java-read-file-line-by-line/#respond Sun, 15 Mar 2020 11:50:42 +0000 https://java2blog.com/?p=8810 In this post, we will see different ways to read file line by line in java.

Sometimes, we need to read file line by line to a String, and process it.

Here are different ways to read file line by line in java.

Java 8 Streams

Java 8 has introduced a new method called lines() in Files class which can be used to read file line by line.

The advantage of using this approach is that it will return Stream of String which will be populated lazily as Stream is used. In case, you need to read the large file and require only first 1000 lines to read, then this is the best approach as it will not rest of the file in memory which will result in better throughput.

Another advantage is that you can use different Stream methods to perform the operation on Stream such as filter, map, etc.

Let’s see this with the help of an example.

package org.arpit.java2blog;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFileLineByLineMain {

    public static String fileName="/users/apple/";
    public static void main(String[] args) {
        Path filePath = Paths.get("/users/apple/Desktop/employees.txt");

        try (Stream<String> lines = Files.lines( filePath )) 
        {
            lines.forEach(System.out::println);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Let’s say you want print all male employees.You can use filter method to filter all the male employees.

package org.arpit.java2blog;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ReadFileLineByLineMain {

    public static String fileName="/users/apple/";
    public static void main(String[] args) {
        Path filePath = Paths.get("/users/apple/Desktop/employees.txt");

        try (Stream<String> lines = Files.lines( filePath )) 
        {
            List<String> maleEmp = lines.filter(emp -> emp.contains("Male"))
                                     .collect(Collectors.toList());
            maleEmp.forEach(System.out::println);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Using BufferReader

You can use java.io.BufferReader‘s readLine() method to read file into String line by line.Once you reach end of the file, it will return null.

package org.arpit.java2blog;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLineMain {

    public static void main(String[] args) {
        String fileName = "/users/apple/Desktop/employees.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

            String line;
                        //br.readLine() will return null when end of file is reached
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Scanner

You can use java.util.Scanner class to read file line by line. You can use hasNextLine() method to check if there are more lines to read and nextLine() to retrieve current line and move the read position to next line.

package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadFileLineByLineMain {

    public static void main(String[] args) {
        String fileName = "/users/apple/Desktop/employees.txt";

        try (Scanner scanner = new Scanner(new File(fileName))) {

            while (scanner.hasNext()){
                System.out.println(scanner.nextLine());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Scanner class divides its input into token using delimiter, which is either line feed("\n") or carriage return("\r".) in our case.

Using Files

You can use java.nio.file.File ‘s readAllLines method to read file into list of String.

It may not perform well in case you have large file.

package org.arpit.java2blog;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadFileLineByLineMain {

    public static void main(String[] args) {

        ReadFileLineByLineMain rfllm=new ReadFileLineByLineMain();
        String fileName = "/users/apple/Desktop/employees.txt";
        List<String> lines = rfllm.readFileLineByLine(fileName);
         for (String line : lines) {
                System.out.println(line);
            }

    }

    public List<String> readFileLineByLine(String fileName)
    {
        List<String> lines=null;
        try {
            lines = Files.readAllLines(Paths.get(fileName),
                        Charset.defaultCharset());
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
}

Using RandomAccessFile

You can also use RandomAccessFile's readLine() method to read file line by line in java. You need to open file in read mode and then call readLine() method to read file line by line.

package org.arpit.java2blog;

import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadFileLineByLineMain {

    public static String fileName="/users/apple/Desktop/employees.txt";
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile(fileName, "r");
            String str;
            while ((str = file.readLine()) != null) {
                System.out.println(str);
            }
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Apache Commons

In case you prefer to use Apache commons library, you can use FileUtils‘s readLines method to read file into the list.

You need to include following dependencies in pom.xml.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class ReadFileLineByLineMain {

    public static String fileName="/users/apple/Desktop/employees.txt";
    public static void main(String[] args) {
        List lines;
        try {
            lines = FileUtils.readLines(new File(fileName), StandardCharsets.UTF_8);
            lines.forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Please note that this approach may not be well optimized. It will read the complete file into a list which can perform badly in case of large files.

That’s all about how to read file line by line in java.

]]>
https://java2blog.com/java-read-file-line-by-line/feed/ 0