Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Saturday, 29 April 2023

File separator, separatorChar, pathSeparator, pathSeparatorChar in Java

In this post, I am going to explain about 4 properties in ‘java.io.File’ package.

 

a.   File.separatorChar : The system-dependent default name-separator character.  This field is initialized to contain the first character of the value of the system property 'file.separator'.  On UNIX systems the value of this field is '/' on Microsoft Windows systems it is '\\'.

b.   File.separator: Same as separatorChar, but it is a String.

c.    File.pathSeparatorChar: The system-dependent path-separator character.  This field is initialized to contain the first character of the value of the system property 'path.separator'.  This character is used to separate filenames in a sequence of files given as a path list. On UNIX systems, this character is ':', on Microsoft Windows systems it is ';'

d.   File.pathSeparator: Same as pathSeparatorChar, but it is a String.

 

Find the below working application.

 

FileConstantsDemo.java

package com.sample.app.files;

import java.io.File;

public class FileConstantsDemo {

  public static void main(String[] args) {

    System.out.println("Operating System: " + System.getProperty("os.name"));

    System.out.println("File.separatorChar = " + File.separatorChar);
    System.out.println("File.separator = " + File.separator);

    System.out.println("File.pathSeparatorChar = " + File.pathSeparatorChar);
    System.out.println("File.pathSeparator = " + File.pathSeparator);

  }
}

 

Output

Operating System: Mac OS X
File.separatorChar = /
File.separator = /
File.pathSeparatorChar = :
File.pathSeparator = :

 

You may like

file and stream programs in Java

Check whether a directory has some files or not

Check given path is a file and not a symbolic link in Java

Check given path is a directory and not a symbolic link in Java

Convert InputStream to string

Write InputStream to a file in Java

Saturday, 11 February 2023

Write InputStream to a file in Java

In this post, I am going to explain how to write the content of an InputStream to a file.

 


 

 

Approach 1: Using InputStream read method.

public static void writeInputStreamToAFile1(final InputStream inputStream, final String filePath)
        throws IOException {
    checkInput(inputStream, filePath);

    File newFile = new File(filePath);

    // create parent dirs if necessary
    newFile.getParentFile().mkdirs();
    newFile.createNewFile();

    try (FileOutputStream outputStream = new FileOutputStream(newFile, false)) {
        int read;
        byte[] bytes = new byte[65535];
        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
    }

}

Approach 2: Using Files.copy() method.

public static void writeInputStreamToAFile2(final InputStream inputStream, final String filePath)
        throws IOException {
    checkInput(inputStream, filePath);

    File newFile = new File(filePath);

    // create parent dirs if necessary
    newFile.getParentFile().mkdirs();
    newFile.createNewFile();
    Files.copy(inputStream, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

Approach 3: Using InputStream#transferTo method. This method is introduced in Java9.

public static void writeInputStreamToAFile3(final InputStream inputStream, final String filePath)
        throws IOException {
    checkInput(inputStream, filePath);

    File newFile = new File(filePath);

    // create parent dirs if necessary
    newFile.getParentFile().mkdirs();
    newFile.createNewFile();
    try (OutputStream output = new FileOutputStream(newFile, false)) {
        inputStream.transferTo(output);
    }
}

Find the below working application.

 

InputStreamToAFile.java

package com.sample.app;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class InputStreamToAFile {

    private static void checkInput(InputStream inputStream, String filePath) {
        if (inputStream == null) {
            throw new IllegalArgumentException("inputStream is null");
        }

        if (filePath == null) {
            throw new IllegalArgumentException("filePath is null");
        }
    }

    public static void writeInputStreamToAFile1(final InputStream inputStream, final String filePath)
            throws IOException {
        checkInput(inputStream, filePath);

        File newFile = new File(filePath);

        // create parent dirs if necessary
        newFile.getParentFile().mkdirs();
        newFile.createNewFile();

        try (FileOutputStream outputStream = new FileOutputStream(newFile, false)) {
            int read;
            byte[] bytes = new byte[65535];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }

    }

    public static void writeInputStreamToAFile2(final InputStream inputStream, final String filePath)
            throws IOException {
        checkInput(inputStream, filePath);

        File newFile = new File(filePath);

        // create parent dirs if necessary
        newFile.getParentFile().mkdirs();
        newFile.createNewFile();
        Files.copy(inputStream, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    public static void writeInputStreamToAFile3(final InputStream inputStream, final String filePath)
            throws IOException {
        checkInput(inputStream, filePath);

        File newFile = new File(filePath);

        // create parent dirs if necessary
        newFile.getParentFile().mkdirs();
        newFile.createNewFile();
        try (OutputStream output = new FileOutputStream(newFile, false)) {
            inputStream.transferTo(output);
        }
    }

    public static void main(String[] args) throws IOException {
        ByteArrayInputStream bios1 = new ByteArrayInputStream(new String("Hello World").getBytes());
        ByteArrayInputStream bios2 = new ByteArrayInputStream(new String("Hello World").getBytes());
        ByteArrayInputStream bios3 = new ByteArrayInputStream(new String("Hello World").getBytes());

        String file1 = "/Users/Shared/files/file1.txt";
        String file2 = "/Users/Shared/files/file2.txt";
        String file3 = "/Users/Shared/files/file3.txt";

        writeInputStreamToAFile1(bios1, file1);
        writeInputStreamToAFile1(bios2, file2);
        writeInputStreamToAFile1(bios3, file3);
    }

}

Run above application, you can confirm that three files file1, file2 and file3 created with the content of inputstream.



 

You may like

file and stream programs in Java

check whether a file is executable or not in Java

Check whether a directory has some files or not

Check given path is a file and not a symbolic link in Java

Check given path is a directory and not a symbolic link in Java

Convert InputStream to string

Sunday, 27 November 2022

Read file content using BufferedReader in Java

Step 1: Get the instance of FileReader.

final FileReader fileReader = new FileReader(filePath);

 

Step 2: Get the instance of BufferedReader from FileReader.

final BufferedReader bufferedReader = new BufferedReader(fileReader);

 

Step 3: Read the file content using read method of BufferedReader.

final StringBuilder stringBuilder = new StringBuilder();
final char[] charBuffer = new char[65535];
int noOfCharsRead;

while ((noOfCharsRead = bufferedReader.read(charBuffer)) != -1) {
	stringBuilder.append(charBuffer, 0, noOfCharsRead);
}

 

Find the below working application.


FileUtil.java

package com.sample.util;

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

public class FileUtil {

	public static String readText(final String filePath) throws FileNotFoundException, IOException {
		if (filePath == null || filePath.isEmpty()) {
			return "";
		}

		try (final FileReader fileReader = new FileReader(filePath);
				final BufferedReader bufferedReader = new BufferedReader(fileReader)) {

			final StringBuilder stringBuilder = new StringBuilder();

			final char[] charBuffer = new char[65535];

			int noOfCharsRead;
			while ((noOfCharsRead = bufferedReader.read(charBuffer)) != -1) {
				stringBuilder.append(charBuffer, 0, noOfCharsRead);
			}
			return stringBuilder.toString();
		}
	}

}

FileReadDemo.java

package com.sample.app;

import java.io.IOException;

import com.sample.util.FileUtil;

public class FileReadDemo {

	public static void main(final String[] args) throws IOException {
		final String filePath = "/Users/Shared/a.txt";

		System.out.println(FileUtil.readText(filePath));
	}

}

 

You may like

file and stream programs in Java

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to get the directory size in Java?

Convert string to InputStream in Java

Read the data from BufferedReader in Java

Friday, 29 July 2022

How to get the directory size in Java?

Write a program to print the folder or directory size in bytes, KBs, MBs and GBs.

 

Approach 1: Traverse the folder recursively and accumulate all the files size.

 


FolderSize.java

package com.sample.app.files;

import java.io.File;

public class FolderSize {

	private static long getFolderSizeInBytes(final File folder) {
		long lengthInBytes = 0;

		final File[] files = folder.listFiles();

		int count = files.length;

		for (int i = 0; i < count; i++) {
			if (files[i].isFile()) {
				lengthInBytes += files[i].length();
			} else {
				lengthInBytes += getFolderSizeInBytes(files[i]);
			}
		}
		return lengthInBytes;
	}

	private static double bytesToKB(long sizeInBytes) {
		return sizeInBytes / (double) 1024;
	}

	private static double bytesToMB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024);
	}

	private static double bytesToGB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024 * 1024);
	}

	public static void main(String[] args) {
		File folder = new File("/Users/krishna/Documents ");
		long folderSizeInBytes = getFolderSizeInBytes(folder);

		System.out.println("Folder size in bytes : " + folderSizeInBytes);
		System.out.println("Folder size in KB : " + bytesToKB(folderSizeInBytes));
		System.out.println("Folder size in MB : " + bytesToMB(folderSizeInBytes));
		System.out.println("Folder size in GB : " + bytesToGB(folderSizeInBytes));
	}

}

 

Approach 2: Using Files.walkFileTree. Files.walkFileTree method walks a file tree.

 

FolderSize.java

 

package com.sample.app.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicLong;

public class FolderSize {

	private static long getFolderSizeInBytes(final File folder) {

		Path directory = folder.toPath();
		final AtomicLong lengthInBytes = new AtomicLong(0);

		try {
			Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					lengthInBytes.addAndGet(attrs.size());
					return FileVisitResult.CONTINUE;
				}
			});
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}

		return lengthInBytes.longValue();
	}

	private static double bytesToKB(long sizeInBytes) {
		return sizeInBytes / (double) 1024;
	}

	private static double bytesToMB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024);
	}

	private static double bytesToGB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024 * 1024);
	}

	public static void main(String[] args) {
		File folder = new File("/Users/krishna/Documents");
		long folderSizeInBytes = getFolderSizeInBytes(folder);

		System.out.println("Folder size in bytes : " + folderSizeInBytes);
		System.out.println("Folder size in KB : " + bytesToKB(folderSizeInBytes));
		System.out.println("Folder size in MB : " + bytesToMB(folderSizeInBytes));
		System.out.println("Folder size in GB : " + bytesToGB(folderSizeInBytes));
	}

}

 

Approach 3: Using Files.walk method.

 

Files.walk method return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by Path#resolve(Path) resolving the relative path against start.

 

FolderSize.java

 

package com.sample.app.files;

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

public class FolderSize {

	private static long getFolderSizeInBytes(final File folder) {

		Path directory = folder.toPath();

		long lengthInBytes = 0l;
		try {
			lengthInBytes = Files.walk(directory).filter(file -> file.toFile().isFile())
					.mapToLong(file -> file.toFile().length()).sum();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}

		return lengthInBytes;
	}

	private static double bytesToKB(long sizeInBytes) {
		return sizeInBytes / (double) 1024;
	}

	private static double bytesToMB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024);
	}

	private static double bytesToGB(long sizeInBytes) {
		return sizeInBytes / (double) (1024 * 1024 * 1024);
	}

	public static void main(String[] args) {
		File folder = new File("/Users/krishna/Documents");
		long folderSizeInBytes = getFolderSizeInBytes(folder);

		System.out.println("Folder size in bytes : " + folderSizeInBytes);
		System.out.println("Folder size in KB : " + bytesToKB(folderSizeInBytes));
		System.out.println("Folder size in MB : " + bytesToMB(folderSizeInBytes));
		System.out.println("Folder size in GB : " + bytesToGB(folderSizeInBytes));
	}

}

 

You may like

Get the content of resource file as string

Copy the content of file to other location

Write byte array to a file

How to download a binary file in Java?

How to process a huge file line by line in Java?

How to process a large file in chunks?

 


Monday, 25 July 2022

Java: How to process a large file in chunks?

 

This is continuation to my previous post, where I explained how to read a large file line by line in Java.

 

Problem Statement

Read a large file, where the entire data is in single line.

 

Solution

Since all the data is in single line, reading the file line by line will not help us here. We need to read the chunk of data at a time.

 

How to read chunk of data at  time?

BufferedReader#read method used to read the data one chunk at a time.

 


Signature

public int read(char cbuf[], int off, int len)

Reads characters into a portion of an array. This method return the number of characters read, or -1 if the end of the stream has been reached

 

Below snippet read the file data in chunks.

try (final BufferedReader reader = new BufferedReader(new FileReader(new File(inputFilePath)));
		final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
	final char[] ch = new char[65535];

	int noOfCharsRead = -1;
	while ((noOfCharsRead = reader.read(ch, 0, ch.length)) != -1) {

		final String str;
		if (noOfCharsRead != 65535) {
			str = new String(Arrays.copyOf(ch, noOfCharsRead));
		} else {
			str = new String(ch);
		}

		writer.write(transformation.apply(str));

	}

}

 

Above snippet read the file chunk by chubk, apply the transformation on each chunk and write the result to destination.

 

Find the below working application.

 

FileUtil.java
package com.sample.app.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.Function;

public class FileUtil {

	public static void processFile(String inputFilePath, String outputFilePath, Function<String, String> transformation)
			throws FileNotFoundException, IOException {

		try (final BufferedReader reader = new BufferedReader(new FileReader(new File(inputFilePath)));
				final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
			final char[] ch = new char[65535];

			int noOfCharsRead = -1;
			while ((noOfCharsRead = reader.read(ch, 0, ch.length)) != -1) {

				final String str;
				if (noOfCharsRead != 65535) {
					str = new String(Arrays.copyOf(ch, noOfCharsRead));
				} else {
					str = new String(ch);
				}

				writer.write(transformation.apply(str));

			}

		}
	}

}

App.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.function.Function;

import com.sample.app.util.FileUtil;

public class App {
	public static void main(String[] args) throws FileNotFoundException, IOException {

		Function<String, String> toUpper = new Function<String, String>() {

			@Override
			public String apply(String t) {
				return t.toUpperCase();
			}

		};

		FileUtil.processFile("/Users/Shared/a.txt", "/Users/Shared/b.txt", toUpper);

	}
}





You may like

File programs in Java

Get the content of resource file as string

Copy the content of file to other location

Write byte array to a file

How to download a binary file in Java?

How to process a huge file line by line in Java?