JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Locking Files using Java

October 26, 2007 by Krishna Srinivasan Leave a Comment

File Locking can be achieved in java by making use of the New I/O API (nio). Before the advent of New I/O API, there was no direct support in Java for locking a file. It is important to understand that File locking is hugely dependent on the native operating system on which the program is executing.

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

File Locks can either be exclusive or shared. An exclusive lock can be acquired on a file only if there are no processes or applications accessing the file. It is possible for one or more processes to have any number of locks on the same file but in different region of a file in the case of a shared lock. Some operating systems doesn’t support the concept of shared locking.

Java provides lock() and tryLock() methods in FileChannel class for getting a lock over the file object. Whether the lock is an exclusive lock or a shared lock depends on the flavor of the methods taking arguments which represents the region of the file to be locked. The method lock() blocks execution until it gets a lock whereas the method tryLock() doesn’t block and returns immediately. If a lock cannot be cannot be acquired on a file, then the tryLock() method will return null.

FileLockTest.java
[code lang=”java”]
package tips.javabeat.nio.lock;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockTest {

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

RandomAccessFile file = null;
FileLock fileLock = null;
try
{
file = new RandomAccessFile("FileToBeLocked", "rw");
FileChannel fileChannel = file.getChannel();

fileLock = fileChannel.tryLock();
if (fileLock != null){
System.out.println("File is locked");
accessTheLockedFile();
}
}finally{
if (fileLock != null){
fileLock.release();
}
}
}

static void accessTheLockedFile(){

try{
FileInputStream input = new FileInputStream("FileToBeLocked");
int data = input.read();
System.out.println(data);
}catch (Exception exception){
exception.printStackTrace();
}
}
}
[/code]

The above program tries to lock a file called “FileToBeLocked” by calling the lock() method on the associated File Channel object. The lock() method blocks the thread until it gets a lock on the file. Then, in order to ensure that the file is locked, the method accessTheLockedFile() is called which tries to read the file contents. Since the lock acquired is an exclusive lock, an IOException is thrown.

Filed Under: Java Tagged With: File IO

File Upload and Download using Java

October 10, 2007 by Krishna Srinivasan Leave a Comment

File Upload and Download is always a handy utility to know. There will be some need to upload a file to an FTP server, Like if you generate a report or store some data in .xls file, then it needs to be uploaded to a FTP server for further use. like wise we need to download some data (data stored in .xls files)for manuplation from the server in our projects. Here we have the code to do this for us. The FileUploadDownload utility.

also read: follow us on @twitter and @facebook

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials
  • Randomly accessing the file contents

This file has the two classes one for upload a file to the FTP server and the other one for downloading the file from the FTP server. This program is written in very simple and easy startegy to upload or download the files using Java. It is using BufferedOutputStream and BufferedInputStream IO classes. This program can be effectively reuse for your purpose incase if you want to upload or download the files from your website or your project work. If you like the program and feels it is very useful for you, please write comment and let us know if there is any improvement needed in the code.

If you have any doubts on the code and looking for the help on this code, please post your queries in the comments section.

File Upload and Download Code Example

[code lang=”java”]
package com.resource.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* This class is used to upload a file to a FTP server.
*
* @author Muthu
*/
public class FileUpload
{

/**
* Upload a file to a FTP server. A FTP URL is generated with the
* following syntax:
* ftp://user:password@host:port/filePath;type=i.
*
* @param ftpServer , FTP server address (optional port ‘:portNumber’).
* @param user , Optional user name to login.
* @param password , Optional password for user.
* @param fileName , Destination file name on FTP server (with optional
* preceding relative path, e.g. "myDir/myFile.txt").
* @param source , Source file to upload.
* @throws MalformedURLException, IOException on error.
*/
public void upload( String ftpServer, String user, String password,
String fileName, File source ) throws MalformedURLException,
IOException
{
if (ftpServer != null && fileName != null && source != null)
{
StringBuffer sb = new StringBuffer( "ftp://" );
// check for authentication else assume its anonymous access.
if (user != null && password != null)
{
sb.append( user );
sb.append( ‘:’ );
sb.append( password );
sb.append( ‘@’ );
}
sb.append( ftpServer );
sb.append( ‘/’ );
sb.append( fileName );
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file directory
* listing
*/
sb.append( ";type=i" );

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URL url = new URL( sb.toString() );
URLConnection urlc = url.openConnection();

bos = new BufferedOutputStream( urlc.getOutputStream() );
bis = new BufferedInputStream( new FileInputStream( source ) );

int i;
// read byte by byte until end of stream
while ((i = bis.read()) != -1)
{
bos.write( i );
}
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
System.out.println( "Input not available." );
}
}

/**
* Download a file from a FTP server. A FTP URL is generated with the
* following syntax:
* ftp://user:password@host:port/filePath;type=i.
*
* @param ftpServer , FTP server address (optional port ‘:portNumber’).
* @param user , Optional user name to login.
* @param password , Optional password for user.
* @param fileName , Name of file to download (with optional preceeding
* relative path, e.g. one/two/three.txt).
* @param destination , Destination file to save.
* @throws MalformedURLException, IOException on error.
*/
public void download( String ftpServer, String user, String password,
String fileName, File destination ) throws MalformedURLException,
IOException
{
if (ftpServer != null && fileName != null && destination != null)
{
StringBuffer sb = new StringBuffer( "ftp://" );
// check for authentication else assume its anonymous access.
if (user != null && password != null)
{
sb.append( user );
sb.append( ‘:’ );
sb.append( password );
sb.append( ‘@’ );
}
sb.append( ftpServer );
sb.append( ‘/’ );
sb.append( fileName );
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file directory
* listing
*/
sb.append( ";type=i" );
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URL url = new URL( sb.toString() );
URLConnection urlc = url.openConnection();

bis = new BufferedInputStream( urlc.getInputStream() );
bos = new BufferedOutputStream( new FileOutputStream(
destination.getName() ) );

int i;
while ((i = bis.read()) != -1)
{
bos.write( i );
}
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
else
{
System.out.println( "Input not available" );
}
}
}[/code]

Filed Under: Java Tagged With: File IO

Copying File Contents using FileChannel

October 9, 2007 by Krishna Srinivasan Leave a Comment

In this technical tip, let us see an easy way of achieving file copy using File Channels. File Channels are part of Java New I/O Packages. A file can be viewed as a sequence of bytes. The various Buffer classes in New I/O Packages serve as a container for manipulating the primitive byte contents. It is also possible to allocate a new Buffer object, read and write byte data into the existing Buffer using the Buffer classes. The File Channel objects are tightly associated with the Buffer class, and now File objects are coupled with File Channel object which means that it is now possible to perform read and write data on the files using the File Channel objects.

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

The following code snippet will show you how to copy file contents using the File Channel class.

FileCopyUsingFileChannel.java
[code lang=”java”]
package tips.nio.copyusingfc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class FileCopyUsingFileChannel {

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

String thisFile = "./src/tips/nio/copyusingfc/FileCopyUsingFileChannel.java";
FileInputStream source = new FileInputStream(thisFile);
FileOutputStream destination = new FileOutputStream("Output.java");

FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();

long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
}
}

[/code]

In the above program, we have created an input stream and an output stream object. The input stream points to the current java file and the output stream is pointing to Output.java. It is to this Output.java we want the contents of the file to be transferred. As mentioned earlier, a file object is associated with a File Channel object. So, we obtain the File Channel object for both the input and the output stream using the following code,

[code lang=”java”]
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
[/code]

To make the copy operation to happen, we call the FileChannel.transferTo() method on the source file object passing the starting position, the number of bytes to be transferred and the target channel object.

Filed Under: Java Tagged With: File IO

Randomly accessing the file contents

September 25, 2007 by Krishna Srinivasan Leave a Comment

In this techincal tip, let us see how to access the contents of a file randomly instead of the traditional sequential access. Imagine that we want to search for a particular record in a file. If we prefer Sequential access in this case, then it will involve traversing over the file byte by byte and searching for the relevant record. This won’t be an ideal solution particularly if the size of the file is too big. So a mechanism must be there to randomly access the file contents in which case we can use java.io.RandomAccessFile class. The following code tries to open a file for random accessing,

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

[code lang=”java”]
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
[/code]

The first argument passed to the RandomAccessFile constructor is the name of the file name and the second argument specifies the mode in which we want to operate on the open file. Passing "rw" means to open the file in read as well as in write mode. The following code snippet shows how to write some contents within the file.

[code lang=”java”]
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
writeEmployee(file, "John", 35, 54544.43d);
writeEmployee(file, "Jenny", 28, 34544.42d);
writeEmployee(file, "Joesph", 41, 64544.77d);
file.close();
[/code]

In the above code snippet we are trying to write some information (name, age and salary) about employee object. Here is the definition of the writeEmployee() method,

[code lang=”java”]
static void writeEmployee(RandomAccessFile file, String name, int age,
double salary) throws Exception{
file.writeUTF(name);
file.writeInt(age);
file.writeDouble(salary);
}
[/code]

The methods RandomAccessFile.writeUTF(), RandomAccessFile.writeInt() and RandomAccessFile.writeDouble() are used to write string, integer and double data-types respectively. Now, let us look in the following section how to read the written contents back from the file,

[code lang=”java”]
static void readEmployee(RandomAccessFile file) throws Exception{
String name = file.readUTF();
int age = file.readInt();
double salary = file.readDouble();
System.out.println("Name = " + name + ",
Age = " + age + ", Salary = " + salary);
}

[/code]

Till now, we have seen how to write and read sequentially using the RandomAccessFile object. Now, let us see the random access way using the methods getFilePointer() and seek(). The method getFilePointer() returns the current position of the file pointer. Consider the following code snippet,

[code lang=”java”]
RandomAccessFile file = new RandomAccessFile("junk.txt", "rw");

file.writeInt(20);
System.out.println(file.getFilePointer());

file.writeDouble(12345.5454d);
System.out.println(file.getFilePointer());

file.close();

[/code]

We try to write an integer into the file. Since the size of an integer is 4 bytes, the file pointer would be 4 bytes away from the beginning of the file. So, the call to getFilePointer() will return 4. In the next statement, we tried to write some double value into the file and since its size is 8, the file pointer would have got traversed to 4 + 8 = 12. So the call to getFilePointer() will now return 12.

Now let us see the usage of the seek() method. Consider the following code snippet which writes even numbers into the file.

[code lang=”java”]
RandomAccessFile file = new RandomAccessFile("evennumbers.txt", "rw");
int evenNums[] = {0, 2, 4, 7, 10};

for(int evenNum : evenNums){
file.writeInt(evenNum);
}
file.close();

[/code]

In the above code, we have stored the even numbers ranging between 0 and 10 in an array and then written them into a file using the enhanced for loop. Purposely, we have written the number 7 (which is not an even number) into the file. Let us correct this by making use of the seek() method. We know that writing an integer into the file will occupy 4 bytes and the number 7 is written after 3 * 4 = 12 bytes. The following code snippet forwards the file pointer to 12 bytes by using the seek() method and replaces the integer 7 with 8. Then it traverses over the file to read and print the contents to verify the new updated content.

[code lang=”java”]
RandomAccessFile file = new RandomAccessFile("evennumbers.txt", "rw");
// Forward the file pointer to 6 bytes
file.seek(12);

// and write the content.
file.writeInt(8);

file.seek(0);
for(int index = 0; index < 5; index ++){
System.out.println(file.readInt());
}

file.close();

[/code]

Filed Under: Java Tagged With: File IO

Recursively traversing files and folders using Java File API

August 27, 2007 by Krishna Srinivasan Leave a Comment

In this section, let us see how to recursively traverse over files and folders by making use of Java File API. Whether it is a folder or a file, both are represented as a java.io.File object. For example, consider the following code snippet,
[code]
File myFile = new File("C:\myDocuments\myFile.txt"); // Case 1
File myFolder = new File("C:\myDocuments"); // Case 2
[/code]

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

If both files and folders are represented as a single File object, then how can we differentiate between a File and a Folder? The File API provides convenient methods for determining this in the form of File.isDirectory() and File.isFile(). For example, in case 1, File.isDirectory() and File.isFile() returns false and true respectively, whereas for case 2, it is true and false.
For listing all the files in a particular directory, we can use the File.listFiles() method. When operated on a folder, it will return all the files in the File Array object. For example, consider the following code snippet,

[code lang=”java”]
File myFolder = new File("C:\myDocuments");
File allMyFolderObjects[] = myFolder.listFiles();[/code]
In the above case, if we have two files (say file1.txt and file2.txt) and a folder (sub-folder) within myFolder, then the size of allMyFolderObjects will be three. Using the combination of the above methods we have seen, let us write code to recursively traverse over a folder object. Given below is the complete code for the same.
FolderTraversar.java
[code lang=”java”]
package tips.foldertraversal;

import java.io.File;

public class FolderTraversar {
private String indent = "";
private File originalFileObject;
private File fileObject;

public FolderTraversar(File fileObject) {
this.originalFileObject = fileObject;
this.fileObject = fileObject;
}

public void traverse() {
recursiveTraversal(fileObject);
}

public void recursiveTraversal(File fileObject) {
if (fileObject.isDirectory()) {
indent = getIndent(fileObject);
System.out.println(indent + fileObject.getName());
File allFiles[] = fileObject.listFiles();
for (File aFile : allFiles) {
recursiveTraversal(aFile);
}
} else if (fileObject.isFile()) {
System.out.println(indent + " " + fileObject.getName());
}
}

private String getIndent(File fileObject) {
String original = originalFileObject.getAbsolutePath();
String fileStr = fileObject.getAbsolutePath();
String subString = fileStr.substring(original.length(),
fileStr.length());
String indent = "";
for (int index = 0; index < subString.length(); index++) {
char aChar = subString.charAt(index);
if (aChar == File.separatorChar) {
indent = indent + " ";
}
}
return indent;
}
}
[/code]
The above class FolderTraverser accepts a Folder object that we wish to traverse. Then, by calling the FolderTraverser.traverse() method, the folder can be traversed recursively. The implementation of traverse() delegates the control to a private method by name recursiveTraversal(). Initially we are checking whether the File object is a folder by calling the File.isDirectory() method. If so, we print the name of the folder and then retrieves the content of the Folder by calling the File.listFiles() method. The array is again recursively traversed. Note that just to make the output meaningful, we have calculated the indent of the various files and folder items to be displayed.
FolderTraversarTest.java
[code lang=”java”]package tips.foldertraversal;

import java.io.File;

public class FolderTraversarTest {
public static void main(String[] args) {
String folderPath = "F:\Technical Writings\www.javabeat.net\Tips\AllSamples\AllTips\src\tips";
FolderTraversar traversal = new FolderTraversar(new File(folderPath));
traversal.traverse();
}
}[/code]
The output of the above client program is,

[code]
tips
eforloop
EnhancedForLoopTest.java
UDEForLoop.java
pattern
factory
Button.java
ButtonFactory.java
FactoryClient.java
LinuxButton.java
WindowsButton.java
singleton
MyConnection.java
MyConnectionConsumer.java
state
…
…[/code]

Filed Under: Java Tagged With: File IO

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved